dongxi7722 2016-02-26 10:59 采纳率: 0%
浏览 50
已采纳

array_search返回错误的密钥[重复]

This question already has an answer here:

I have this array:

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

and, if I write:

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

I get:

key2

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.

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...

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?

</div>
  • 写回答

4条回答 默认 最新

  • douyou8266 2016-02-26 11:10
    关注

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

    array_search is using == to compare values during search

    FORM PHP DOC

    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.

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

    Simple Test

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

    Solution use strict option to search identical values

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

    Output

    string(4) "key3"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭