jpstrikesback jpstrikesback - 2 months ago 7
PHP Question

in_array() does not work

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.

Answer

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