A helper function for retrieving a value from an object or array
I'm a sucker for neat little utility functions that make my life as a developer so much simpler. Here's one I use on a regular basis. It has earned a place in my general_helper file, next to the dump functions.
Doing isset() dozens of times in every view file really gets on my nerves. So here's a helper function I use on a regular basis. I posted the code below, but you can find the latest version as a gist on Github.
https://gist.github.com/4064663 ›
/** * 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; } }