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?
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .
To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With