【问题标题】:array_search does not work as expected [duplicate]array_search 没有按预期工作[重复]
【发布时间】:2012-11-01 01:25:18
【问题描述】:

我有以下数组:

$array = array (
    'a' => 'A',
    'b' => 'B',
    'c' => 'C'
);

我想了解这种行为:

// true, normal behaviour, there is a 'A' value in my array
echo array_search('A', $array) === 'a';

// true, normal behaviour, there is no 1 value in my array
echo array_search(1, $array) === false;

// true ???? there is no 0 as value in my array
echo array_search(0, $array) === 'a';

为什么array_search(0, $array) 返回我数组的第一个键?

【问题讨论】:

    标签: php arrays type-conversion


    【解决方案1】:

    来自 PHP 文档

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

    大多数人不知道array_search 默认使用== 如果你想搜索相同的元素,你需要添加一个严格的参数......这是什么意思?

    如果你使用

    array_search(0, $array) //it would use == and 0 == 'A'
    

    你需要的是

    array_search(0, $array,true) // it would compare with === 0 !== 'A'
                             ^------------ Strict 
    

    【讨论】:

    • 我刚刚检查过,'A' == 0 你是对的。奇怪的行为。
    • var_dump(0 == 'A'); 将是 true 由于类型转换
    • 行为在这里解释:php.net/manual/en/language.operators.comparison.php(第一个例子:0 == "a"
    • 好的,我记住了。这就像C中的atoi,“123string”将转换为123。没关系!谢谢。
    • 是的var_dump(123 == "123string");是真的.....
    猜你喜欢
    • 2014-12-17
    • 2011-12-01
    • 1970-01-01
    • 2021-08-14
    • 2013-03-25
    • 2021-01-16
    • 2015-10-16
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多