tags:

views:

41

answers:

4

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
}
+6  A: 

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 ;-)

Pascal MARTIN
`Note I used the !== operator, that does a type-sensitive comparison` - that's exactly what the problem was. 0 was evaluating to false... thanks
Derek Adair
You're welcome :-) ;; I've edited my answer to add links to some other relevant pages of the manual, btw :-)
Pascal MARTIN
thanks, you rock!
Derek Adair
A: 

From the docs:

Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.

oggy
A: 

array_search will return FALSE if nothing is found. If it DOES find the needle it will return the array key for the needle.

More info at: http://php.net/manual/en/function.array-search.php

manyxcxi
A: 

if you're just checking if the value exists, in_array is the way to go.

stereofrog