2

Why does this return true.

$needle = TRUE;
$haystack = array('that', 'this');

print in_array($needle, $haystack); // 1

EDIT: I am aware that one can pass in_array() the strict parameter to check types. I want to know why specifically the behaviour I show is exhibited.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
jpstrikesback
  • 2,300
  • 14
  • 18
  • what do you want to find in array, a boolean variable or boolean string? Base on documentation **If needle is a string, the comparison is done in a case-sensitive manner.** – Javad Apr 26 '14 at 01:26
  • 2
    See the explanation on [`in_array`](http://www.php.net/manual/en/function.in-array.php) and its third parameter, `$strict`. – mario Apr 26 '14 at 01:26
  • I know I can pass in_array() the strict param, but I wanted an answer to my question (which I have below now). – jpstrikesback Apr 26 '14 at 03:38
  • This is not a duplicate as far as I can tell. I am not asking how to fix this, I am asking why this is this way. See the accepted answer. – jpstrikesback Apr 26 '14 at 04:02

1 Answers1

3

Any non-empty string in PHP is equal to TRUE when loose comparison is made (i.e. type is ignored). You may test this by doing:

var_dump('this' == TRUE);
var_dump('that' == TRUE);

DEMO

But the results are quite different when strict comparison is made (i.e. type is taken into consideration):

var_dump('this' === TRUE);
var_dump('that' === TRUE);

DEMO

In order to enforce strict comparison in the function in_array, you have to set the optional third parameter to TRUE:

$needle = TRUE;
$haystack = array('that', 'this');

var_dump(in_array($needle, $haystack, TRUE));

DEMO

Sharanya Dutta
  • 3,981
  • 2
  • 17
  • 27
  • Nice explanation. I understand that one can pass the strict param to compare types, I just wanted to understand the somewhat non-intuitive behaviour I encountered. FWIW I am passing the bool back in a return to a function I don't control (drupal hookesque invocation) wherein lies the in_array(). See [!in_Array() here](http://drupalcode.org/project/commerce_cardonfile.git/blob/075dc820077794fe8283b0c7159a63020f2ef53b:/commerce_cardonfile.module#l1457) – jpstrikesback Apr 26 '14 at 03:56