PHP: in_array strict mode
Today I stumbled upon a problem in a legacy software I have to maintain. Given the following snippet:
$cats = $config->get('todos/important_categories');
if(in_array($given_cat, $cats)) {
# do something
}
$given_cat was "hobby" and $cats was array('news', 'fun', 0).
I don't know who put the 0 into the configuration and it doesn't
matter. But what matters is that the in_array call returned
true. While I suspected that the type system was the problem, I
checked the manual page. It says:
Searches haystack for needle using loose comparison unless strict is set.
That basically means that in_array() uses == to compare the search
value and the current array element. And since strings that can't be
parsed to numbers are converted to 0 when compared to an integer:
➜ ckruse@vali ~ % php -r 'var_dump(0 == "abc");'
bool(true)
➜ ckruse@vali ~ % php -r 'var_dump("abc" == 0);'
bool(true)
➜ ckruse@vali ~ %
this gave me true for the last element. To avoid that one has to use
the third parameter for in_array, defaulting to false:
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.
So the correct version of the snippet above would be this:
$cats = $config->get('todos/important_categories');
if(in_array($given_cat, $cats, true)) {
# do something
}
Since I didn't know about the $strict parameter I thought it might
be useful to write a short post about it.