1

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 ?

Anri
  • 1,706
  • 2
  • 17
  • 36

2 Answers2

4

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Why 'sitepoint.com' == true is true ? I confused :) – Anri Jul 22 '14 at 14:08
  • 1
    @Anri: Because what PHP is doing when you do `in_array` is loop over the array and compare your passed value to the values in the array. When it gets to `true`, it does `'sitepoint.com' == true`. These 2 types are not the same, so it needs to convert them. You are comparing a string to a boolean, so it converts the string to a boolean so that they are the same types. In the docs, it explains how this works (http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting). So `'sitepoint.com' == true` becomes `(bool)'sitepoint.com' == true` which is `true == true`. – gen_Eric Jul 22 '14 at 14:30
  • thank you @Rocket Hazmat for good explenation – Anri Jul 22 '14 at 14:31
3

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.

cf the docs

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149