PHP,in_array,0值 [英] Php, in_array, 0 value

查看:121
本文介绍了PHP,in_array,0值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是想了解下一个场景的 in_array 行为:

I was trying to understand the in_array behavior at the next scenario:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
var_dump(in_array(0, $arr));

in_array()的返回值是一个布尔真正。正如你可以看到有值等于 0 ,所以如果能有一个人,请帮助我理解为什么函数返回真的吗?

The returned value of the in_array() is boolean true. As you can see there is no value equal to 0, so if can some one please help me understand why does the function return true?

推荐答案

这是一个已知的问题,在每次的的文档。请看下面的例子:

This is a known issue, per the comments in the documentation. Consider the following examples:

in_array(0, array(42));      // FALSE
in_array(0, array('42'));    // FALSE
in_array(0, array('Foo'));   // TRUE

要避免这种情况,提供第三放慢参数,真正,将在比较中的严格模式的将不仅是价值,而且种类比较结果为好:

To avoid this, provide the third paramter, true, placing the comparison in strict mode which will not only compare values, but types as well:

var_dump(in_array(0, $arr, true));

其他的变通办法存在不必要每张支票被放置在严格模式:

Other work-arounds exist that don't necessitate every check being placed in strict-mode:

in_array($value, $my_array, empty($value) && $value !== '0');

为什么?

后面所有的的原因是很可能<一个href=\"http://php.net/manual/en/language.types.string.php#language.types.string.conversion\">string-to-number转换的。如果我们试图从再见得到一个数字,我们得到 0 ,这是我们在问到查表的值。

But Why?

The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from "Bye", we are given 0, which is the value we're asking to look-up.

echo intval("Bye"); // 0

要确认这一点,我们可以使用 array_search 找到关联的密钥的匹配的值:

To confirm this, we can use array_search to find the key that is associated with the matching value:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
echo array_search(0, $arr);

在此,返回的关键是 2 ,这意味着 0 在<$ C的转换被发现$ C>细则为整数。

In this, the returned key is 2, meaning 0 is being found in the conversion of Bye to an integer.

这篇关于PHP,in_array,0值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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