2

In the below in_array(0, $array) evaluates to true. That surprised me. I expected false.

I know adding the third parameter to indicate a strict check like in_array(0, $array, true) will give me the desired result.

That said, I'm very curious why in_array(0, $array) evaluates to true. At first I thought it was just seeing a string at the 0 index, but in_array(1, $array) evaluates to false so that doesnt seem to explain it.

Example: Runable fiddle here

<?php 

$array = [
    'inputs',
    'app',
    'post',
    'server',
];

echo in_array('inputs', $array) ? '"inputs" is in the array...' : '';
echo "\n";

echo in_array(0, $array) ? '0 is also in the array!' : '';
echo "\n";

echo in_array(1, $array) ? '1 is also in the array!' : '1 is NOT in the array!';

Output:

"inputs" is in the array...
0 is also in the array!     <---- huh? 
1 is NOT in the array!
Community
  • 1
  • 1
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133

1 Answers1

2

It's because by default in_array uses loose comparisons, so when you pass 0 as an input it attempts to convert the string values in the array to an integer, and they all come out as 0 (because none of them start with a digit; see the manual), causing in_array to return true. It returns false for an input of 1 because all the comparison values are 0.

You will see similar behaviour with array_keys:

print_r(array_keys($array, 0));

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)

indicating that array_keys thinks every value in the array is 0.

If you use the strict parameter to in_array or array_keys you will avoid this issue i.e.

echo in_array(0, $array, true) ? '0 is also in the array!' : '0 is NOT in the array!';
print_r(array_keys($array, 0, true));

Output:

0 is NOT in the array!
Array
(
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95