I was trying to understand the in_array
behavior at the next scenario:
$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey'); var_dump(in_array(0, $arr));
The returned value of the in_array()
is boolean true
. As you can see there is no value equal to 0
, so if can some one please help me understand why does the function return true?
Advertisement
Answer
This is a known issue, per the comments in the documentation. Consider the following examples:
in_array(0, array(42)); // FALSE in_array(0, array('42')); // FALSE in_array(0, array('Foo')); // TRUE
To avoid this, provide the third paramter, true
, placing the comparison in strict mode which will not only compare values, but types as well:
var_dump(in_array(0, $arr, true));
Other work-arounds exist that don’t necessitate every check being placed in strict-mode:
in_array($value, $my_array, empty($value) && $value !== '0');
But Why?
The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from “Bye”, we are given 0
, which is the value we’re asking to look-up.
echo intval("Bye"); // 0
To confirm this, we can use array_search
to find the key that is associated with the matching value:
$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey'); echo array_search(0, $arr);
In this, the returned key is 2
, meaning 0
is being found in the conversion of Bye
to an integer.