PHP in_array()/array_search()奇怪的行为 [英] PHP in_array() / array_search() odd behaviour

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

问题描述

我在使用PHP函数in_array()时发现了一些奇怪的行为.我有一个像这样的数组:

I have found some odd behaviour while I was using the PHP function in_array(). I have an array like this:

$arr = [TRUE, "some string", "something else"];

现在,如果我要检查数组中是否包含"test",显然不是,但是in_array()仍返回TRUE,为什么呢?

Now if I want to check if "test" is in the array it is clearly not, but in_array() still returns TRUE, why is that?

$result = in_array("test", $arr);
var_dump($result);  //Output: bool(true)

使用array_search()时也会发生相同的事情:

The same thing happens when using array_search():

$result = array_search("test", $arr);
var_dump($result);  //Output: int(0)

我认为也许数组中的TRUE值会自动导致该函数为每个结果返回TRUE,而不检查数组的其余部分,但是我找不到任何文档来暗示这种非常奇怪的功能.

I thought maybe that the value TRUE in the array was automatically causing the function to return TRUE for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.

推荐答案

此功能的行为 array_search() 不是错误,而是有据可查的行为.

This behaviour of the function in_array() and array_search() is not a bug, but instead well documented behaviour.

两个函数都有一个名为$strict的第三个可选参数,默认情况下为FALSE:

Both functions have a 3rd optional parameter called $strict which by default is FALSE:

bool in_array(混合$ needle,array $ haystack [,bool $ strict = FALSE] )

mixed array_search(混合$ needle,array $ haystack [,bool $ strict = false] )

现在这意味着默认情况下,两个函数都使用松散(==)比较来比较值.因此,它们仅在PHP类型变通之后检查值是否在 之后相同,而不检查类型.因此,在您的示例中,TRUE == "any none emtpy string"的计算结果为TRUE.

Now what that means is that by default both functions use loosely(==) comparison to compare the values. So they only check if the values are the same after PHP type juggling and without checking the type. Because of that in your example TRUE == "any none emtpy string" evaluates to TRUE.

因此,通过在调用函数时将第3个参数设置为TRUE,可以说PHP应该使用strict(===)比较,并且在比较时应该检查值和值的类型.

So by setting the 3rd parameter to TRUE while calling the function you say that PHP should use strict(===) comparison and it should check value AND type of the values while comparing.

请参阅以下内容: PHP相等(==双重等于)和身份(===三次等于)比较运算符有何不同?

这篇关于PHP in_array()/array_search()奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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