April 24, 2012
PHP – array_search() fails on === true, but not on !== false?
Question by DaBananaboat
When I want to check if something is in the array and get the key back, I use the array_search() function.
Why is it when I compare the function to be exactly equal to true (=== true) it returns false, and when I compare it to not be exactly equal to false (!== false) it returns true?
<?php
if(array_search($value, $array) === true)
{
// Fails
}
if(array_search($value, $array) !== false)
{
// Succeeds
}
?>
Thanks in advance.
Answer by Starx
array_search()
does not return true.
If will only return false, if it can’t find anything, otherwise it will return the key of the matched element.
According to the manual
array_search — Searches the array for a given value and returns the corresponding key if successful
….Returns the key for needle if it is found in the array, FALSE otherwise.