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 parame开发者_开发知识库ter 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_exists
instead of isset
for the second condition. Isset will return false if $a[$key] === null
which is problematic if you've intentionally set $a[$key] = null
. Of course, this isn't a huge deal unless you set a $default
value to something other than NULL
.
function array_get($a, $key, $default=NULL)
{
if (isset($a) and array_key_exists($key, $a))
return $a[$key];
else
return $default;
}
$foo = (isset($_SESSION['foo'])) ? $_SESSION['foo'] : NULL;
精彩评论