Skip to content

Instantly share code, notes, and snippets.

@joostvanveen
Created November 13, 2012 08:30
Show Gist options
  • Save joostvanveen/4064663 to your computer and use it in GitHub Desktop.
Save joostvanveen/4064663 to your computer and use it in GitHub Desktop.
Helper function that returns the value for a key in an array or a property in an object. No more endless isset() statements.
<?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;
}
}
@macnux
Copy link

macnux commented May 8, 2013

Hi
i put the file in helpers folder and call it in my controller like that
$this->load->helper ( 'MY_helper' );
$mm ['address'] = "something";
$this->load->view ( 'welcome_message', $mm );

and in my view
i try to get the value of address like this
echo get_key($mm, 'address');
but it gives error says

Undefined variable: mm

@joostvanveen
Copy link
Author

I'm afraid that has nothing to do with the helper function. You need to pass the variable to the view correctly :)

$this->load->view ( 'welcome_message', array('mm' => $mm );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment