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

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

问题描述

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

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

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

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

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

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

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

解决方案

函数的这种行为 in_array()array_search() 不是错误,而是有据可查的行为.

这两个函数都有一个名为 $strict 的可选参数,默认为 FALSE:

<块引用>

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

<块引用>

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

现在这意味着默认情况下两个函数都使用松散的(==)比较来比较值.所以他们只检查值是否相同 PHP 类型杂耍而不检查类型.因为在您的示例中 TRUE == "any none emtpy string" 评估为 TRUE.

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

将此作为参考:PHP 等式(== 双等式)和恒等式(=== 三等式)比较运算符有何不同?

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"];

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)

The same thing happens when using array_search():

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

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.

解决方案

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

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

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

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

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.

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.

See this as a reference: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

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

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