What is the best way to access unknown array elements without generating PHP notice?

前端 未结 2 2012
既然无缘
既然无缘 2020-12-10 21:34

If I have this array,

ini_set(\'display_errors\', true);
error_reporting(E_ALL);

$arr = array(
  \'id\' => 1234,
  \'name\' => \'Jack\',
  \'email\' =         


        
相关标签:
2条回答
  • 2020-12-10 21:39

    I borrowed the code below from Kohana. It will return the element of multidimensional array or NULL (or any default value chosen) if the key doesn't exist.

    function _arr($arr, $path, $default = NULL) 
    {
      if (!is_array($arr))
        return $default;
    
      $cursor = $arr;
      $keys = explode('.', $path);
    
      foreach ($keys as $key) {
        if (isset($cursor[$key])) {
          $cursor = $cursor[$key];
        } else {
          return $default;
        }
      }
    
      return $cursor;
    }
    

    Given the input array above, access its elements with:

    echo _arr($arr, 'id');                    // 1234
    echo _arr($arr, 'city.country.name');     // USA
    echo _arr($arr, 'city.name');             // Los Angeles
    echo _arr($arr, 'city.zip', 'not set');   // not set
    
    0 讨论(0)
  • 2020-12-10 22:02

    The @ error control operator suppresses any errors generated by an expression, including invalid array keys.

    $name = @$arr['city']['country']['name'];
    
    0 讨论(0)
提交回复
热议问题