A problem about in_array A problem about in_array arrays arrays

A problem about in_array


It means you have to set the third parameter to true when you want the comparison to not only compare values, but also types.

Else, there is type conversions, while doing the comparisons -- see String conversion to numbers, for instance.

As a matter of fact, in_array without and with strict is just the same difference as you'll have between == and === -- see Comparison Operators.


This conversion, most of the time, works OK... But not in the case you're trying to compare 0 with a string that starts with a letter : the string gets converted to a numeric, which has 0 as value.


The “default” mode of in_array is using a loose comparison like the == comparison operator does. That means 0 is compared like this:

var_dump(0 == 'a');  // bool(true)var_dump(0 == 'b');  // bool(true)var_dump(0 == 'c');  // bool(true)

Now the loose comparison operator == is using string conversion to integer before actually comparing the values:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

And 'a', 'b' and 'c' are all converted to 0:

var_dump((int) 'a');  // int(0)var_dump((int) 'b');  // int(0)var_dump((int) 'b');  // int(0)

But when using in_array in strict mode (set third parameter to true), a strict comparison (===) is done, that means both the value and type must be equal:

var_dump(0 === 'a');  // bool(false)var_dump(0 === 'b');  // bool(false)var_dump(0 === 'c');  // bool(false)

So when using the in_array in strict mode, you’re getting the expected result:

var_dump(in_array(0, $a, true));  // bool(false)


In your first example, every value of the array $a, when converted to numeric, is 0. That's why your first example results in "a bingo".

You don't have to use the strict parameter if you know you rely on implicit conversion, or that your datatypes are the same ( e.g. searching for a string in an array of string ). Otherwise you should use the strict parameter, the same you should use === instead of == when comparing two values that must be of the same type.