Starting with PHP 7, there is a new operator specifically designed for these cases called the Null Coalesce Operator .
So now you can do:
echo $items['four']['a'] ?? 99;
instead
echo isset($items['four']['a']) ? $items['four']['a'] : 99;
There is another way to do this before PHP 7:
function get(&$value, $default = null) { return isset($value) ? $value : $default; }
And the following will work without problems:
echo get($item['four']['a'], 99); echo get($item['five'], ['a' => 1]);
But note that when using this method, calling an array property for a value that is not an array will throw an error. for example
echo get($item['one']['a']['b'], 99); // Throws: PHP warning: Cannot use a scalar value as an array on line 1
In addition, there is a case when a fatal error will be issued:
$a = "a"; echo get($a[0], "b");
In the end, there is an unpleasant workaround, but it works almost well (in some cases, the problems described below occur):
function get($value, $default = null) { return isset($value) ? $value : $default; } $a = [ 'a' => 'b', 'b' => 2 ]; echo get(@$a['a'], 'c'); // prints 'c' -- OK echo get(@$a['c'], 'd'); // prints 'd' -- OK echo get(@$a['a'][0], 'c'); // prints 'b' -- OK (but also maybe wrong - it depends) echo get(@$a['a'][1], 'c'); // prints NULL -- NOT OK echo get(@$a['a']['f'], 'c'); // prints 'b' -- NOT OK echo get(@$a['c'], 'd'); // prints 'd' -- OK echo get(@$a['c']['a'], 'd'); // prints 'd' -- OK echo get(@$a['b'][0], 'c'); // prints 'c' -- OK echo get(@$a['b']['f'], 'c'); // prints 'c' -- OK echo get(@$b, 'c'); // prints 'c' -- OK