4

Could someone explain to me why that is true?

in_array('', array(0,1,2));
0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worth including this table as well: php.net/manual/en/…
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.