Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in array search

Tags:

arrays

php

search

I am trying to find values inside an array. This array always starts with 0. unfortunately array_search start searching with the array element 1. So the first element is always overlooked.

How could I "shift" this array to start with 1, or make array-search start with 0? The array comes out of an XML web service, so I can not rally modify the results.

like image 663
Mac Taylor Avatar asked Feb 01 '10 20:02

Mac Taylor


Video Answer


1 Answers

array_search does not start searching at index 1. Try this example:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('blue', $array);  // $key = 0
?>

Whatever the problem is with your code, it's not that it's first element is index 0.

It's more likely that you're use == instead of === to check the return value. If array_search returns 0, indicating the first element, the following code will not work:

// doesn't work when element 0 is matched!
if (false == array_search(...)) { ... }

Instead, you must check using ===, which compares both value and type

// works, even when element 0 is matched
if (false === array_search(...)) { ... }
like image 190
meagar Avatar answered Oct 20 '22 22:10

meagar