【问题标题】:Weird array_search behaviour [duplicate]奇怪的array_search行为[重复]
【发布时间】:2014-12-29 20:55:56
【问题描述】:

我有以下代码:

<?php 

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

?>

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

【问题讨论】:

    标签: php


    【解决方案1】:

    这是因为array_search 使用== 来比较事物。这使得 PHP convert 操作数,以便它们的类型匹配。

    1 == "I want to find this text"
    "aa" == "I want to find this text"
    0 == "I want to find this text"
    

    在第一个和第三个中,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)

    第三个参数告诉array_search 改用===。这转换类型,而是比较它们。这将为您提供FALSE,因为在 类型和值中没有任何内容与 "I want to find this text" 匹配。

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 1970-01-01
      • 2013-06-28
      • 2015-07-26
      • 2020-04-26
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多