Index Index - 1 year ago 109
PHP Question

in_array() always returns TRUE

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

Above example gives following result:

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

matches needle 0 to any given haystack?

Answer Source

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".


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download