in php the following code returns true
$array = array(
'isReady' => false,
'isPHP' => true,
'isStrange' => true
);
var_dump(in_array('sitepoint.com', $array));
result is a true
WHY ?
in php the following code returns true
$array = array(
'isReady' => false,
'isPHP' => true,
'isStrange' => true
);
var_dump(in_array('sitepoint.com', $array));
result is a true
WHY ?
Because of the 3rd parameter to in_array
, $strict
.
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
By default it's FALSE
, which makes it use ==
.
'sitepoint.com' == true
That's actually true (because of PHP's type juggling)!
You want to do:
in_array('sitepoint.com', $array, TRUE);
That will make it use ===
.
'sitepoint.com' === true
That's not true.
in_array
performs loose comparison (value checking only, not type & value). Since your array values are all booleans (true
and false
), the search string ("sitepoint.com") is being coerced to a boolean, effectively, your code translates to:
var_dump(in_array((bool)'sitepoint.com', array(true, false, true)));
Since a string, when cast to bool
is true
, in_array
returns true
.
To force type and value checking, pass true
as third argument to in_array
.