奇怪的array_search行为

Vol*_*bal -2 php

我有以下代码:

<?php 

    $ray = array(1, "aa" , 0);
    echo "Index = " . array_search("I want to find this text", $ray);

?>
Run Code Online (Sandbox Code Playgroud)

如何解释该array_search()函数返回现有索引2?

Roc*_*mat 5

这是因为array_search使用==比较的东西.这使得PHP 转换操作数以使它们的类型匹配.

1 == "I want to find this text"
"aa" == "I want to find this text"
0 == "I want to find this text"
Run Code Online (Sandbox Code Playgroud)

在第一个和第三个,PHP需要转换"I want to find this text"为一个数字,以便它可以比较.将字符串转换为数字时,PHP从字符串的开头读取并停在第一个非数字字符处.所以"I want to find this text"转换为0.

所以比较是

1 == "I want to find this text" => 1 == 0 => false
"aa" == "I want to find this text" => false
0 == "I want to find this text" => 0 == 0 => true
Run Code Online (Sandbox Code Playgroud)

而且,这就是为什么你得到2.

要解决此问题,请执行此操作: array_search("I want to find this text", $ray, true)

第三个参数告诉array_search使用===.这并没有进行类型转换,而是太对它们进行比较.这会给你FALSE因为没有相匹配"I want to find this text"两个类型和值.