Skip to content

Instantly share code, notes, and snippets.

@erunion
Created February 23, 2016 22:27
Show Gist options
  • Save erunion/a8ff8baf96764a7ff6af to your computer and use it in GitHub Desktop.
Save erunion/a8ff8baf96764a7ff6af to your computer and use it in GitHub Desktop.
<?php
/**
* Safely get a value by key from an array (without creating a notice)
* @param array|object $array - can be an array or object
* @param int|string|array $keys - if array, performs a deep fetch on a multidemensional array|object
* @param mixed $default - if $keys do not exist in $array, this value is returned
* @return mixed - The value at $keys, or else $default
* @throws Exception if $keys is not a scalar or array
*/
if (!function_exists('fetch')) {
function fetch($array, $keys, $default = null)
{
// most often, $keys will be a scalar, so a direct key check on $array should be used to maximize performance
if (is_scalar($keys)) {
if (array_key_exists($keys, $array)) {
return is_object($array) ? $array->$keys : $array[$keys];
}
return $default;
}
// less often, $keys is an array, which triggers deep fetching
if (!is_array($keys)) {
throw new \Exception('$keys must be a scalar or an array');
}
foreach ($keys as $key) {
if (array_key_exists($key, $array)) {
$array = is_object($array) ? $array->$key : $array[$key];
} else {
return $default;
}
}
return $array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment