PHP how to access deeply nested array values

Accessing deeply nested array values can be tedious because you have to check if each level of the array exists before getting to the value you're interested in.

Well, that is not an issue if you're using PHP 7's null coalesce operator. Here is how it works.

Example one

$place = $earth ?? 'not here';

echo $place; // 'not here'

$place will be the string 'not here' because $earth is not defined. No errors thrown!

Example two

$earth = [
  'northAmerica' => [
    'usa' => [
      'pa' => [
        'philadelphia' => "You've found me"
      ]
    ]
  ]
];

$place = $earth['europe']['france']['paris'] ?? 'not here';

echo $place; // 'not here'

$place will be the string 'not here' because $earth['europe'] doesn't exist.

Example three

$earth = [
  'northAmerica' => [
    'usa' => [
      'pa' => [
        'philadelphia' => "You've found me"
      ]
    ]
  ]
];

$place = $earth['northAmerica']['usa']['pa']['philadelphia'] ?? 'not here';

echo $place; // "You've found me"

$place will be the string "You've found me"

PHP 5

For PHP 5, you can use the help of array_reduce() to keep your code concise.

$earth = [
  'northAmerica' => [
    'usa' => [
      'pa' => [
        'philadelphia' => "You've found me"
      ]
    ]
  ]
];

$place = array_reduce(['northAmerica', 'usa', 'pa', 'philadelphia'], function($result, $index) {
  if ($result && !is_null($index)) {
    return (array_key_exists($index, $result)) ? $result[$index] : null;
  }
}, $earth);

echo $place; // "You've found me"