If I have this array,
ini_set(\'display_errors\', true);
error_reporting(E_ALL);
$arr = array(
\'id\' => 1234,
\'name\' => \'Jack\',
\'email\' =
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
The @
error control operator suppresses any errors generated by an expression, including invalid array keys.
$name = @$arr['city']['country']['name'];