简体   繁体   English

从PHP数组安全地读取值的好的策略是什么?

[英]What is a good strategy for safely reading values out of a PHP array?

I'm trying to read values from $_SESSION which may or may not be set, while avoiding undefined index warnings. 我正在尝试从$ _SESSION读取可能设置或未设置的值,同时避免出现未定义的索引警告。 I'm used to Python dicts, which have a d.get('key','default') method, which returns a default parameter if not found. 我习惯了Python字典,该字典具有d.get('key','default')方法,如果找不到该方法,则会返回默认参数。 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. 对于第二个条件,我将使用array_key_exists而不是isset Isset will return false if $a[$key] === null which is problematic if you've intentionally set $a[$key] = null . 如果$a[$key] === null ,Isset将返回false,如果您有意设置$a[$key] = null那么这是有问题的。 Of course, this isn't a huge deal unless you set a $default value to something other than NULL . 当然,除非您将$default值设置为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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM