tags:

views:

36

answers:

2

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?

+2  A: 
$foo = (isset($_SESSION['foo'])) ? $_SESSION['foo'] : NULL;
Pickle
I was expecting an "Undefined variable" warning if the session wasn't started, but I didn't get it (PHP 5.3.1). I guess `isset()` handles both "Undefined variable" and "Undefined index" warnings.
jwhitlock
+3  A: 

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;
}
thetaiko
On the other hand `array_key_exists` involves a function call. Furthermore many people want `null` to be treated as `unset`.
nikic
I guess subtleties like this is why there isn't One True Solution built into PHP.
jwhitlock
@nikic - OP stated that they were used to the Python dict.get() method. This is a more accurate representation of that functionality where if the key, value pair is `'a':None` and you called `x.get('a', 'a null value')` the return would be `None` and NOT `'a null value'`
thetaiko