Index Index - 2 months ago 24
PHP Question

in_array() always returns TRUE

$arrValue = array('first', 'second');
$ret = in_array(0, $arrValue);
var_dump($ret);
var_dump($arrValue);


Above example gives following result:

bool(true)
array(2) {
[0]=> string(5) "first"
[1]=> string(6) "second"
}


Why
in_array()
matches needle 0 to any given haystack?

Answer

That's because the function uses a non-strict comparison. The string in the array is compared to integer 0. Some typecasting is happening with data loss, and both are regarded the same:

var_dump(0 == 'first'); //  bool(true)

So solve this, you can use the third parameter and set it to true to request strict comparison.

$ret = in_array(0, $arrValue, true);

Keep in mind, through, that strict is really strict. In a strict comparison, 0 is not equal to "0".

Docs: http://nl3.php.net/in_array

Comments