有没有一种更好的PHP方法可以通过数组(字典)通过键获取默认值?
在Python中,可以做到:
foo = {}
assert foo.get('bar', 'baz') == 'baz'
在PHP中,可以使用三元运算符,如下所示:
$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz');
我正在寻找高尔夫球版。 我可以在PHP中做得更好一点吗?
8个解决方案
47 votes
时间在流逝,PHP在不断发展。 PHP 7现在支持空合并运算符??:
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
Ivan Yarych answered 2020-06-29T21:18:50Z
44 votes
我只是想出了这个小辅助函数:
function get(&$var, $default=null) {
return isset($var) ? $var : $default;
}
这不仅适用于字典,而且适用于各种变量:
$test = array('foo'=>'bar');
get($test['foo'],'nope'); // bar
get($test['baz'],'nope'); // nope
get($test['spam']['eggs'],'nope'); // nope
get($undefined,'nope'); // nope
每个引用传递以前未定义的变量不会导致$var错误。 相反,通过引用传递$var将对其进行定义,并将其设置为get($var)。如果传递的变量为get($var),也会返回默认值。另请注意,垃圾邮件/鸡蛋示例中隐式生成的数组:
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的副本,而不是引用。 我希望这有帮助!
stepmuel answered 2020-06-29T21:18:30Z
20 votes
将错误控制运算符@与三元运算符的PHP 5.3快捷方式版本结合使用:
$bar = @$foo['bar'] ?: 'defaultvalue';
romanlv answered 2020-06-29T21:19:10Z
8 votes
我发现创建这样的函数很有用:
function array_value($array, $key, $default_value = null) {
return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default_value;
}
并像这样使用它:
$params = array('code' => 7777, 'name' => "Cloud Strife");
$code = array_value($params, 'code');
$name = array_value($params, 'name');
$weapon = array_value($params, 'weapon', "Buster Sword");
$materia = array_value($params, 'materia');
echo "{ code: $code, name: $name, weapon: $weapon, materia: $materia }";
在这种情况下,默认值为null,但您可以将其设置为所需的值。
我希望它是有用的。
rbento answered 2020-06-29T21:19:43Z
5 votes
一种“稍微”骇客的方式:
$foo = array();
var_dump('baz' == $tmp = &$foo['bar']);
$foo['bar'] = 'baz';
var_dump('baz' == $tmp = &$foo['bar']);
[HTTP://code pad.viper-7.com/F LX HC H]
显然,这并不是真正的好方法。 但这在其他情况下很方便。 例如。 我经常这样声明GET和POST变量的快捷方式:
$name =& $_GET['name'];
// instead of
$name = isset($_GET['name']) ? $_GET['name'] : null;
PS:可以将其称为“内置==$_=&特殊比较运算符”:
var_dump('baz' ==$_=& $foo['bar']);
PPS:嗯,您显然可以使用
var_dump('baz' == @$foo['bar']);
但这甚至比==$_=&操作员还差。 您知道,人们不太喜欢错误抑制运算符。
NikiC answered 2020-06-29T21:20:25Z
5 votes
PHP 5.3具有三元运算符的快捷方式版本:
$x = $foo ?: 'defaultvaluehere';
这基本上是
if (isset($foo)) {
$x = $foo;
else {
$x = 'defaultvaluehere';
}
否则,没有更短的方法。
Marc B answered 2020-06-29T21:20:54Z
2 votes
如果您通过数组中的键枚举默认值,则可以通过以下方式完成:
$foo = array('a' => 1, 'b' => 2);
$defaults = array('b' => 55, 'c' => 44);
$foo = array_merge($defaults, $foo);
print_r($foo);
结果是:
Array
(
[b] => 2
[c] => 44
[a] => 1
)
您枚举的默认键/值对越多,代码高尔夫就变得越好。
Rusty Fausak answered 2020-06-29T21:21:22Z
0 votes
“ Marc B”提出了一种使用三元快捷键??的解决方案,但它仍然发出通知。 也许这是一个误会,也许他的意思是? 或者它是在PHP 7发行之前编写的。根据三元描述:
从PHP 5.3开始,可以省略三元运算符的中间部分。 如果expr1的计算值为TRUE,则表达式??返回isset,否则为expr3。
但它不会在内部使用??并发出通知。为避免产生通知,最好使用Null合并运算符??,该运算符在其中使用isset。 在PHP 7中可用。
表达式(expr1)?? 如果expr1为NULL,则(expr2)的计算结果为expr2,否则为expr1。 特别是,如果左侧值不存在,则此运算符不会发出通知,就像isset()一样。 这在阵列键上特别有用。
Example#5分配默认值
// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';
// The above is identical to this if/else statement
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else {
$action = 'default';
}
?>
Alexander Cherkendov answered 2020-06-29T21:22:01Z