【问题标题】:How can I check if an array element exists?如何检查数组元素是否存在?
【发布时间】:2010-12-30 06:51:10
【问题描述】:

示例:我正在检查是否存在这样的数组元素:

if (!self::$instances[$instanceKey]) {
    $instances[$instanceKey] = $theInstance;
}

但是,我不断收到此错误:

注意:未定义的索引:在第 16 行的 /Applications/MAMP/htdocs/mysite/MyClass.php 中进行测试

当然,我第一次想要实例时,$instances 不会知道密钥。我猜我对可用实例的检查是错误的?

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用语言构造 isset 或函数 array_key_exists

    isset 应该快一点(因为它不是函数),但如果元素存在并且值为 NULL,则返回 false。


    例如,考虑这个数组:

    $a = array(
        123 => 'glop', 
        456 => null, 
    );
    

    而这三个测试,依赖于isset

    var_dump(isset($a[123]));
    var_dump(isset($a[456]));
    var_dump(isset($a[789]));
    

    第一个会得到你(元素存在,并且不为空)

    boolean true
    

    虽然第二个会得到你(元素存在,但为空)

    boolean false
    

    最后一个会得到你(元素不存在)

    boolean false
    


    另一方面,像这样使用array_key_exists

    var_dump(array_key_exists(123, $a));
    var_dump(array_key_exists(456, $a));
    var_dump(array_key_exists(789, $a));
    

    你会得到这些输出:

    boolean true
    boolean true
    boolean false
    

    因为,在前两种情况下,元素存在——即使在第二种情况下它为 null。而且,当然,在第三种情况下,它不存在。


    对于像你这样的情况,我通常使用isset,考虑到我从来没有在第二种情况下......但是现在选择使用哪一个取决于你;-)

    例如,您的代码可能会变成这样:

    if (!isset(self::$instances[$instanceKey])) {
        $instances[$instanceKey] = $theInstance;
    }
    

    【讨论】:

    • 我不得不抱怨,因为isset 是错字不安全的。调用$form = [1 => 5]; var_dump(isset($from[1])); 返回false,因为$from 不存在并且E_NOTICE 甚至不会通知您。更慢,但更安全 array_key_exists 为我做这件事。
    【解决方案2】:

    array_key_exists() 比 isset() 慢。这两者的组合(见下面的代码)会有所帮助。

    它利用isset()的性能优势,同时保持正确的检查结果(即即使数组元素为NULL也返回TRUE)

    if (isset($a['element']) || array_key_exists('element', $a)) {
           //the element exists in the array. write your code here.
    }
    

    基准比较:(摘自以下博文)。

    array_key_exists() only : 205 ms
    isset() only : 35ms
    isset() || array_key_exists() : 48ms
    

    http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/http://thinkofdev.com/php-isset-and-multi-dimentional-array/

    详细讨论。

    【讨论】:

    • 而且,isset 也具有误导性。为什么一个名为“is set”的关键字会在实际设置变量或数组位置时返回 false - 即使它设置为 null
    【解决方案3】:

    您可以使用函数array_key_exists 来做到这一点。

    例如,

    $a=array("a"=>"Dog","b"=>"Cat");
    if (array_key_exists("a",$a))
      {
      echo "Key exists!";
      }
    else
      {
      echo "Key does not exist!";
      }
    

    PS : 示例取自here

    【讨论】:

      【解决方案4】:

      你可以使用 isset() 来做这件事。

      $myArr = array("Name" => "Jonathan");
      print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
      

      【讨论】:

        【解决方案5】:

        根据 PHP 手册,您可以通过两种方式执行此操作。这取决于您需要检查的内容。

        如果要检查给定的键或索引是否存在于数组中,请使用 array_key_exists

        <?php
            $search_array = array('first' => 1, 'second' => 4);
            if (array_key_exists('first', $search_array)) {
                echo "The 'first' element is in the array";
            }
        ?>
        

        如果要检查数组中是否存在值,请使用 in_array

        <?php
            $os = array("Mac", "NT", "Irix", "Linux");
            if (in_array("Irix", $os)) {
                echo "Got Irix";
            }
        ?>
        

        【讨论】:

          【解决方案6】:

          您想使用 array_key_exists 函数。

          【讨论】:

            【解决方案7】:

            一个小轶事来说明array_key_exists的使用。

            // A programmer walked through the parking lot in search of his car
            // When he neared it, he reached for his pocket to grab his array of keys
            $keyChain = array(
                'office-door' => unlockOffice(),
                'home-key' => unlockSmallApartment(),
                'wifes-mercedes' => unusedKeyAfterDivorce(),
                'safety-deposit-box' => uselessKeyForEmptyBox(),
                'rusto-old-car' => unlockOldBarrel(),
            );
            
            // He tried and tried but couldn't find the right key for his car
            // And so he wondered if he had the right key with him.
            // To determine this he used array_key_exists
            if (array_key_exists('rusty-old-car', $keyChain)) {
                print('Its on the chain.');
            }
            

            【讨论】:

              【解决方案8】:

              您也可以使用 array_keys 来表示出现次数

              <?php
              $array=array('1','2','6','6','6','5');
              $i=count(array_keys($array, 6));
              if($i>0)
               echo "Element exists in Array";
              ?>
              

              【讨论】:

                猜你喜欢
                • 2015-07-31
                • 2015-09-02
                • 1970-01-01
                • 1970-01-01
                • 2012-02-23
                • 1970-01-01
                • 1970-01-01
                • 2022-01-14
                • 2013-09-17
                相关资源
                最近更新 更多