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?
This is a known issue, per the comments in the documentation. Consider the following examples:
To avoid this, provide the third paramter,
true, placing the comparison in strict mode which will not only compare values, but types as well:Other work-arounds exist that don’t necessitate every check being placed in strict-mode:
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.To confirm this, we can use
array_searchto find the key that is associated with the matching value:In this, the returned key is
2, meaning0is being found in the conversion ofByeto an integer.