Skip to content

Instantly share code, notes, and snippets.

@oscaralexander
Last active March 9, 2017 14:33
Show Gist options
  • Save oscaralexander/3f89b1735220eca253234d911b439e27 to your computer and use it in GitHub Desktop.
Save oscaralexander/3f89b1735220eca253234d911b439e27 to your computer and use it in GitHub Desktop.
Get a value from an associative array or object, or return default.
<?php
/**
* Get a value from an associative array or object, or return default.
*
* @param string $key Dot-separated path to key you wish to extract.
* @param array|object $hash Associative array or object.
* @param mixed $default Value to return if key is non-existent.
* @param bool $is_int Only return key if value is integer.
* @return mixed
*
* @example $email = get('email', $_POST);
* @example $email = get('response.author.email', $json);
*/
function get($key, $hash, $default = null, $is_int = false)
{
if (!is_array($hash) && !is_object($hash)) {
return $default;
}
$hash = (array) $hash;
$keys = explode('.', $key);
$key = array_shift($keys);
$return = $default;
if (isset($hash[$key])) {
$return = $hash[$key];
if (count($keys)) {
return get(implode('.', $keys), $hash[$key], $default, $is_int);
} else {
$return = $is_int ? (is_numeric($return) ? (int) $return : $default) : $return;
}
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment