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 }
The array_search() function searches an array for a given value and returns the key. The function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.
Explanation: The array_search() function searches an array for a specified value, returning its key if located and FALSE otherwise.
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 ;-)
if you're just checking if the value exists, in_array is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With