PHP in_array Gotcha When Searching for 0
I came across a situation this week whilst using the in_array
function that confused me a little bit but, on hindsight, should have been obvious. As I have gotten into the habit of documenting things that I have learnt in this blog, so here it is.
The in_array
function (nicely documented here), simply searches for an item in an array and returns true
or false
accordingly. Consider the following code:
$array = ['a', 'b', 'c'];
var_dump(in_array('b', $array));
var_dump(in_array('z', $array));
var_dump(in_array(1, $array));
Running this will of course have the following output:
bool(true)
bool(false)
bool(false)
So far so good. How about this:
var_dump(in_array(0, $array));
This outputs:
bool(true)
This surprised me greatly because, as you can see, 0 is not in the array and so I would expect it to return false
like it would with any other integer. So what is going on?
Well it is all to do with the fact that PHP is loosely typed. Consider this:
var_dump(0 == 'a');
This would return bool(true)
. Why? Because "a" is being automatically cast as an integer and whenever you try cast a letter as an integer you get 0.
To avoid this, you would want to check the type as well as the content, using the ===
notation:
var_dump(0 === 'a');
Returns bool(false)
.
in_array
is the equivilent of using ==
and so every letter in my array was being cast as an integer and so giving 0. This is why it was returning true.
To avoid this problem, in_array
has a third parameter that tells it to use strict typing (i.e. use ===
instead). So:
var_dump(in_array(0, $array, true));
gives the expected:
bool(false)
Just another small thing to watch out for.
The information for this came from this StackOverflow question, and this blog post. So thanks to both of them.