in_array()始终返回TRUE [英] in_array() always returns TRUE

查看:127
本文介绍了in_array()始终返回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"
}

为什么in_array()将针0匹配到任何给定的干草堆?

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

推荐答案

这是因为该函数使用了非严格比较.将数组中的字符串与整数0进行比较.某些类型转换由于数据丢失而发生,并且两者都被视为相同:

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)

因此,您可以使用第三个参数并将其设置为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);

请牢记,严格是非常严格的.严格比较,0不等于"0".

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

文档: http://nl3.php.net/in_array

这篇关于in_array()始终返回TRUE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆