Skip to content

Instantly share code, notes, and snippets.

@DevotionGeo
Forked from joostvanveen/get_key.php
Last active August 29, 2015 14:20
Show Gist options
  • Save DevotionGeo/757bc261b73d55507d2f to your computer and use it in GitHub Desktop.
Save DevotionGeo/757bc261b73d55507d2f to your computer and use it in GitHub Desktop.
<?php
/**
* Return the value for a key in an array or a property in an object.
* Typical usage:
*
* $object->foo = 'Bar';
* echo get_key($object, 'foo');
*
* $array['baz'] = 'Bat';
* echo get_key($array, 'baz');
*
* @param mixed $haystack
* @param string $needle
* @param mixed $default_value The value if key could not be found.
* @return mixed
*/
function get_key ($haystack, $needle, $default_value = '')
{
if (is_array($haystack)) {
// We have an array. Find the key.
return isset($haystack[$needle]) ? $haystack[$needle] : $default_value;
}
else {
// If it's not an array it must be an object
return isset($haystack->$needle) ? $haystack->$needle : $default_value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment