array_search返回错误的密钥 [英] array_search return wrong key

查看:64
本文介绍了array_search返回错误的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组:

$ar = [ 'key1'=>'John', 'key2'=>0, 'key3'=>'Mary' ];

并且,如果我写:

$idx = array_search ('Mary',$ar);
echo $idx;

我得到:

key2

我已经在网上搜索了,这不是孤立的问题.似乎在关联数组包含0值时,如果未设置严格参数,array_search将失败.

I have searched over the net and this is not isolate problem. It seems that when an associative array contains a 0 value, array_search fails if strict parameter is not set.

还有不只一个错误警告,全部被动机拒绝:"array_search()确实默认情况下是一个宽松的比较."

There are also more than one bug warnings, all rejected with motivation: "array_search() does a loose comparison by default".

好的,我使用严格的参数解决了我的小问题...

Ok, I resolve my little problem using strict parameter...

但是我的问题是:有一个正当的,正当的理由,为什么要作宽松的比较'Mary'==0 'two'==0 还是仅仅是另一个php疯狂? >

But my question is: there is a decent, valid reason why in loose comparison 'Mary'==0 or 'two'==0 or it is only another php madness?

推荐答案

您需要将第三个参数设置为true才能使用严格比较.请看下面的解释:

You need to set third parameter as true to use strict comparison. Please have a look at below explanation:

array_search在搜索过程中使用==比较值

array_search is using == to compare values during search

表格PHP DOC

如果将第三个参数strict设置为TRUE,则array_search()函数将在干草堆中搜索相同的元素.这意味着它还将检查大海捞针中的针的类型,并且对象必须是同一实例.

If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also check the types of the needle in the haystack, and objects must be the same instance.

由于第二个元素是0,因此在搜索过程中字符串已转换为0

Becasue the second element is 0 the string was converted to 0 during search

简单测试

var_dump("Mary" == 0); //true
var_dump("Mary" === 0); //false

解决方案使用strict选项搜索相同的值

Solution use strict option to search identical values

$key = array_search("Mary", $ar,true);
                                  ^---- Strict Option
var_dump($key);

输出

string(4) "key3"

这篇关于array_search返回错误的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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