是否有来自阵列(字典)通过键获取默认值的更好的方式PHP? [英] Is there a better PHP way for getting default value by key from array (dictionary)?
问题描述
在的Python 的人可以做的:
foo = {}
assert foo.get('bar', 'baz') == 'baz'
在 PHP 的人可以去一个三元opeartor为:
In PHP one can go for a trinary opeartor as in:
$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz');
我要寻找一个高尔夫版本。我能做到这一点在PHP短/更好?
I am looking for a golf version. Can I do it shorter/better in PHP?
推荐答案
我刚刚想出了这个小助手功能:
I just came up with this little helper function:
function get(&$var, $default=null) {
return isset($var) ? $var : $default;
}
这不仅工作字典,而是对所有类型的变量:
Not only does this work for dictionaries, but for all kind of variables:
$test = array('foo'=>'bar');
get($test['foo'],'nope'); // bar
get($test['baz'],'nope'); // nope
get($test['spam']['eggs'],'nope'); // nope
get($undefined,'nope'); // nope
传递一个previously未定义的变量元参不引起的通知
错误。相反,通过 $ VAR
引用将定义它,它设置为空
。的默认值也随之如果传递的变量是空
返回。还要注意隐式生成的数组中的垃圾邮件/鸡蛋例如:
Passing a previously undefined variable per reference doesn't cause a NOTICE
error. Instead, passing $var
by reference will define it and set it to null
. The default value will also be returned if the passed variable is null
. Also note the implicitly generated array in the spam/eggs example:
json_encode($test); // {"foo":"bar","baz":null,"spam":{"eggs":null}}
$undefined===null; // true (got defined by passing it to get)
isset($undefined) // false
get($undefined,'nope'); // nope
请注意,即使 $ VAR
通过引用传递,结果的get($ VAR)
将 $ VAR的副本
,而不是引用。我希望这有助于!
Note that even though $var
is passed by reference, the result of get($var)
will be a copy of $var
, not a reference. I hope this helps!
这篇关于是否有来自阵列(字典)通过键获取默认值的更好的方式PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!