array_search无法按预期工作

Ala*_*blo 1 php arrays type-conversion

我有以下数组:

$array = array (
    'a' => 'A',
    'b' => 'B',
    'c' => 'C'
);
Run Code Online (Sandbox Code Playgroud)

我想了解这种行为:

// 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';
Run Code Online (Sandbox Code Playgroud)

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

Bab*_*aba 5

来自PHP DOC

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

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

如果你使用

array_search(0, $array) //it would use == and 0 == 'A'
Run Code Online (Sandbox Code Playgroud)

你需要的是什么

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