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.
Advertisement
Answer
As an alternative to ===
and !==
, you can also use in_array
:
if (in_array($needle, $haystack))