I’m trying to read values from $_SESSION which may or may not be set, while avoiding undefined index warnings. I’m used to Python dicts, which have a d.get('key','default') method, which returns a default parameter if not found. I’ve resorted to this:
function array_get($a, $key, $default=NULL)
{
if (isset($a) and isset($a[$key]))
return $a[$key];
else
return $default;
}
$foo = array_get($_SESSION, 'foo');
if (!$foo) {
// Do some foo initialization
}
Is there a better way to implement this strategy?
I would use
array_key_existsinstead ofissetfor the second condition. Isset will return false if$a[$key] === nullwhich is problematic if you’ve intentionally set$a[$key] = null. Of course, this isn’t a huge deal unless you set a$defaultvalue to something other thanNULL.