php search array key and get value

后端 未结 4 1876
失恋的感觉
失恋的感觉 2020-12-09 08:36

I was wondering what is the best way to search keys in an array and return it\'s value. Something like array_search but for keys. Would a loop be the best way?

Arra

相关标签:
4条回答
  • 2020-12-09 08:37

    Here is an example straight from PHP.net

    $a = array(
        "one" => 1,
        "two" => 2,
        "three" => 3,
        "seventeen" => 17
    );
    
    foreach ($a as $k => $v) {
        echo "\$a[$k] => $v.\n";
    }
    

    in the foreach you can do a comparison of each key to something that you are looking for

    0 讨论(0)
  • 2020-12-09 08:38
    array_search('20120504', array_keys($your_array));
    
    0 讨论(0)
  • 2020-12-09 08:41

    The key is already the ... ehm ... key

    echo $array[20120504];
    

    If you are unsure, if the key exists, test for it

    $key = 20120504;
    $result = isset($array[$key]) ? $array[$key] : null;
    

    Minor addition:

    $result = @$array[$key] ?: null;
    

    One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

    Update: With PHP7 my previous example is possible without the error-silencer

    $result = $array[$key] ?? null;
    
    0 讨论(0)
  • 2020-12-09 09:03
    <?php
    
    // Checks if key exists (doesn't care about it's value).
    // @link http://php.net/manual/en/function.array-key-exists.php
    if (array_key_exists(20120504, $search_array)) {
      echo $search_array[20120504];
    }
    
    // Checks against NULL
    // @link http://php.net/manual/en/function.isset.php
    if (isset($search_array[20120504])) {
      echo $search_array[20120504];
    }
    
    // No warning or error if key doesn't exist plus checks for emptiness.
    // @link http://php.net/manual/en/function.empty.php
    if (!empty($search_array[20120504])) {
      echo $search_array[20120504];
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题