奇怪的array_search行为

时间:2014-12-29 20:55:56

标签: php

我有以下代码:

<?php 

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

?>

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

1 个答案:

答案 0 :(得分: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"

在第1和第3版中,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

而且,这就是你得到2的原因。

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

第3个参数告诉array_search使用===。这样做转换类型,而是比较它们。这样会为您FALSE,因为 类型和值中的"I want to find this text"都不匹配。

相关问题