The buggiest PHP function
by bhartsock on May.16, 2007, under PHP, Programming
Well, its not really PHP’s fault. array_search is misused by developers more than any other PHP function I have seen. Just today, I found two bugs caused by misinformed developers using the function. I myself am also guilty of using this function incorrectly.
The problem lies in array_search‘s return value if the needle isn’t found in the haystack. If the needle isn’t found, array_search returns false. In my experience, many other libraries return -1 in this case. Nevertheless, false and 0 evaluate to the same boolean value, which is where the problem lies.
For example, the following code will not work how you might think:
while(array_search($value, $array)){ .... } while($key = array_search($value, $array)){ ... }
In the first example, in_array should be used for simplicities sake. In the second example, you must use the identical comparison operator (=== or !==). So, when using array_search, be careful not to make any wrong assumptions.