1 is not in array(), the code is expected to return FALSE instead of TRUE. Do you know why?
<?php
var_dump(in_array(1, array('1:foo'))); // TRUE, why?
var_dump(in_array('1', array('1:foo'))); // FALSE
1 is not in array(), the code is expected to return FALSE instead of TRUE. Do you know why?
<?php
var_dump(in_array(1, array('1:foo'))); // TRUE, why?
var_dump(in_array('1', array('1:foo'))); // FALSE
As @knittl already said, this is because type coercion. What is happening:
var_dump(in_array(1, array('1:foo')));
//PHP is going to try to cast '1:foo' to an integer, because your needle is an int.
The cast is (int)'1:foo' which results to the integer 1, so practically we got this:
var_dump(in_array(1, array(1))); //Which is TRUE
And the second statement is false. It's false because they are both the same type and PHP doesn't try any cast anymore. And ofcourse "1" is not the same as "1:foo"
var_dump(in_array('1', array('1:foo'))); //Which is FALSE
Because you are comparing int
to string
, and the string is type-casted to int
- and since first (or any first seq of chars) element of that string is a number and next is not part of any int representation - it change to that element = 1.
http://php.net/manual/en/language.types.type-juggling.php
var_dump(in_array(1233, array('1233:123'))); //also True