If 0 could be a possible key returned from array_search(), what would be the best method for testing if an element exists in an array using this function (or any php function; if there's a better one, please share)?
I was trying to do this:
if(array_search($needle, $haystack)) //...
But that would of course return false if $needle is the first element in the array. I guess what I'm asking is is there some trick I can do in this if statement to get it to behave like I want it? I tried doing these, but none of them worked:
$arr = array(3,4,5,6,7);
if(array_search(3, $arr) != false) //...
if(array_search(3, $arr) >= 0) //...
Appreciate the help.
This is the way:
if(array_search(3, $arr) !== false)
Note the use of the === PHP operator, called identical (not identical in this case). You can read more info in the official doc. You need to use it because with the use of the equal operator you can't distinguish 0 from false (or null or '' as well).
A better solution if you find the match and want to use the integer value is:
if (($pos = array_search(3, $arr)) !== false)
{
// do stuff using $pos
}
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