phparrays

What does array_search() return if nothing was found?


What does array_search() return if nothing was found?

I have the need for the following logic:

$found = array_search($needle, $haystack);

if($found){
  //do stuff
} else {
  //do different stuff
}

Solution

  • Quoting the manual page of array_search() :

    Returns the key for needle if it is found in the array, FALSE otherwise.


    Which means you have to use something like :

    $found = array_search($needle, $haystack);
    
    if ($found !== false) {
        // do stuff
        // when found
    } else {
        // do different stuff
        // when not found
    }
    

    Note I used the !== operator, that does a type-sensitive comparison ; see Comparison Operators, Type Juggling, and Converting to boolean for more details about that ;-)