Search code examples
phparrayssearchzero

php array_search 0 index


It seems that that you can not use the search_array function in PHP to search the 0 index AND have it evalute as true.

Consider this code for example:

$test=array(100, 101, 102, 103);

if($key=array_search(100,$test)){

     echo $key;

}

else{

     echo "Not found";

} 

The needle '100' is found in the haystack and the key is returned as 0. So far so good, but then when I evaluate whether the search was successful or not it fails because the returned value is 0, equal to false!

The php manual suggests using '!==' but by doing so the key (array index) is not returned, instead either 1 or 0 is returned:

if($key=(array_search(103,$test)!== false)){

}

So how can I successfully search the array, find a match in the 0 index and have it evaluate as true?


Solution

  • This is explicitly mentioned in the docs. You need to use === or !==:

    $key = array_search(...);
    
    if ($key !== false) ...
    

    Otherwise, when $key is 0, which evaluates to false when tested as a boolean.