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
}
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
}
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 ;-)
From the docs:
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
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
if you're just checking if the value exists, in_array is the way to go.