代码之家  ›  专栏  ›  技术社区  ›  Derek Adair

[php]:如果未找到任何内容,array_search()返回什么?

  •  13
  • Derek Adair  · 技术社区  · 15 年前

    如果未找到任何内容,array_search()返回什么?

    我需要以下逻辑:

    $found = array_search($needle, $haystack);
    
    if($found){
      //do stuff
    } else {
      //do different stuff
    }
    
    5 回复  |  直到 7 年前
        1
  •  38
  •   Pascal MARTIN    15 年前

    引用 手册第页,共页 array_search() :

    如果是,则返回针的键 在数组中找到, FALSE 否则 .


    这意味着你必须使用类似于:

    $found = array_search($needle, $haystack);
    
    if ($found !== false) {
        // do stuff
        // when found
    } else {
        // do different stuff
        // when not found
    }
    

    注意我用了 !== 运算符,执行类型敏感比较;请参见 Comparison Operators , Type Juggling Converting to boolean 更多细节;-)

        2
  •  3
  •   user187291    15 年前

    如果你只是检查这个值是否存在, in_array 是一条路。

        3
  •  1
  •   oggy    15 年前

    从文档中:

    在Haystack中搜索指针并返回键(如果在数组中找到),否则为false。

        4
  •  1
  •   ashurexm    15 年前

    如果未找到任何内容,数组搜索将返回false。如果它找到了针,它将返回针的数组键。

    更多信息请访问: http://php.net/manual/en/function.array-search.php

        5
  •  1
  •   Jaime Montoya    7 年前

    根据官方文件 http://php.net/manual/en/function.array-search.php :

    警告此函数可能返回布尔值false,但也可能返回 计算结果为false的非布尔值。请阅读 布尔人需要更多信息。使用===运算符测试 此函数的返回值。

    请参见以下示例:

    $foundKey = array_search(12345, $myArray);
    if(!isset($foundKey)){
        // If $myArray is null, then $foundKey will be null too.
        // Do something when both $myArray and $foundKey are null.
    } elseif ($foundKey===false) {
        // $myArray is not null, but 12345 was not found in the $myArray array.
    }else{
        // 12345 was found in the $myArray array.
    }