4

Could someone explain to me why that is true?

in_array('', array(0,1,2));
Broda Noel
  • 1,760
  • 1
  • 19
  • 38

2 Answers2

9

Because, as said in the docs:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

... and '' == 0 is true in PHP. If you want to use strict comparison, just call in_array() with three params:

in_array('', array(0, 1, 2), true); // false

... so the types will be checked as well, and String '' won't have a chance to match against Numbers.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Worth including this table as well: http://php.net/manual/en/types.comparisons.php#types.comparisions-loose – haim770 Dec 28 '14 at 08:37
2

in_array by default performs loose comparison. Thus '' is equivalent to 0.

There is third argument (boolean) to in_array function which says if the matching is to be performed in STRICT way or not.

if you do in_array('', array(0,1,2), TRUE); then the result will be false.

Refer the documentation

Kelsadita
  • 1,038
  • 8
  • 21