flowfree flowfree - 1 year ago 61
PHP Question

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

If I have this array,

ini_set('display_errors', true);

$arr = array(
'id' => 1234,
'name' => 'Jack',
'email' => 'jack@example.com',
'city' => array(
'id' => 55,
'name' => 'Los Angeles',
'country' => array(
'id' => 77,
'name' => 'USA',

I can get the country name with

$name = $arr['city']['country']['name'];

But if the country array doesn't exist, PHP will generate warning:

Notice: Undefined index ... on line xxx

Sure I can do the test first:

if (isset($arr['city']['country']['name'])) {
$name = $arr['city']['country']['name'];
} else {
$name = ''; // or set to default value;

But that is inefficient. What is the best way to get

without generating PHP Notice if it doesn't exist?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download