有没有更好的 PHP 方法可以通过键从数组(字典)中获取默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6696425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:01:29  来源:igfitidea点击:

Is there a better PHP way for getting default value by key from array (dictionary)?

phparrayskeydefault-valuelanguage-design

提问by Yauhen Yakimovich

In Pythonone can do:

Python 中,你可以这样做:

foo = {}
assert foo.get('bar', 'baz') == 'baz'

In PHPone can go for a trinary operator as in:

PHP 中,可以使用三元运算符,如下所示:

$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz');

I am looking for a golf version. Can I do it shorter/better in PHP?

我正在寻找高尔夫版本。我可以在 PHP 中做得更短/更好吗?

UPDATE [March 2020]:

更新 [2020 年 3 月]:

It seems that Null coalescing operator ??is worth checking outtoday.

这似乎Null coalescing operator ??值得一试的今天。

found in the comments below (+1)

在下面的评论中找到 (+1)

采纳答案by stepmuel

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

Passing a previously undefined variable per reference doesn't cause a NOTICEerror. Instead, passing $varby 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:

每个引用传递以前未定义的变量不会导致NOTICE错误。相反,通过$var引用传递将定义它并将其设置为null. 如果传递的变量是 ,也会返回默认值null。还要注意 spam/eggs 示例中隐式生成的数组:

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

Note that even though $varis passed by reference, the result of get($var)will be a copy of $var, not a reference. I hope this helps!

请注意,即使$var通过引用传递, 的结果也get($var)将是 的副本$var,而不是引用。我希望这有帮助!

回答by Ivan Yarych

Time passes and PHP is evolving. PHP 7 now supports the null coalescing operator, ??:

时间在流逝,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';

回答by romanlv

Use the error control operator @with the PHP 5.3 shortcut version of the ternary operator:

将错误控制运算符@与三元运算符的 PHP 5.3 快捷版本一起使用

$bar = @$foo['bar'] ?: 'defaultvalue';

回答by rbento

I find it useful to create a function like so:

我发现创建这样的函数很有用:

function array_value($array, $key, $default_value = null) {
    return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default_value;
}

And use it like this:

并像这样使用它:

$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 }";

The default value in this case is null, but you may set it to whatever you need.

在这种情况下null,默认值为,但您可以将其设置为您需要的任何值。

I hope it is useful.

我希望它有用。

回答by Marc B

PHP 5.3 has a shortcut version of the ternary operator:

PHP 5.3 有一个三元运算符的快捷版本:

$x = $foo ?: 'defaultvaluehere';

which is basically

这基本上是

if (isset($foo)) {
   $x = $foo;
else {
   $x = 'defaultvaluehere';
}

Otherwise, no, there's no shorter method.

否则,不,没有更短的方法。

回答by NikiC

A "slightly" hacky way to do it:

一种“稍微”hacky 的方式来做到这一点:

<?php
    $foo = array();
    var_dump('baz' == $tmp = &$foo['bar']);
    $foo['bar'] = 'baz';
    var_dump('baz' == $tmp = &$foo['bar']);

http://codepad.viper-7.com/flXHCH

http://codepad.viper-7.com/flXHCH

Obviously this isn't really the nice way to do it. But it is handy in other situations. E.g. I often declare shortcuts to GET and POST variables like that:

显然,这并不是真正的好方法。但它在其他情况下很方便。例如,我经常像这样声明 GET 和 POST 变量的快捷方式:

<?php
    $name =& $_GET['name'];
    // instead of
    $name = isset($_GET['name']) ? $_GET['name'] : null;

PS: One could call this the "built-in ==$_=&special comparison operator":

PS:可以将其称为“内置==$_=&特殊比较运算符”:

<?php
    var_dump('baz' ==$_=& $foo['bar']);

PPS: Well, you could obviously just use

PPS:嗯,你显然可以使用

<?php
    var_dump('baz' == @$foo['bar']);

but that's even worse than the ==$_=&operator. People don't like the error suppression operator much, you know.

但这甚至比==$_=&运营商还要糟糕。你知道,人们不太喜欢错误抑制运算符。

回答by Rusty Fausak

If you enumerate the default values by key in an array, it can be done this way:

如果您通过数组中的键枚举默认值,则可以通过以下方式完成:

$foo = array('a' => 1, 'b' => 2);
$defaults = array('b' => 55, 'c' => 44);

$foo = array_merge($defaults, $foo);

print_r($foo);

Which results in:

结果是:

Array
(
    [b] => 2
    [c] => 44
    [a] => 1
)

The more key/value pairs that you enumerate defaults for, the better the code-golf becomes.

您枚举默认值的键/值对越多,代码高尔夫变得越好。

回答by Alexander Cherkendov

There was a solution proposed by "Marc B"to use ternary shortcut $x = $foo ?: 'defaultvaluehere';but it still gives notices. Probably it's a mistyping, maybe he meant ?? or it were written before PHP 7 release. According to Ternary description:

由“马克·B”提出了一个解决方案,以使用三元快捷方式$x = $foo ?: 'defaultvaluehere';,但它仍然给通知。可能是打错字了,也许他是这个意思??或者它是在 PHP 7 发布之前编写的。根据三元描述

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3returns expr1if expr1evaluates to TRUE, and expr3otherwise.

自 PHP 5.3 起,可以省略三元运算符的中间部分。如果计算结果为,则表达式expr1 ?: expr3返回,否则返回。expr1expr1TRUEexpr3

But it doesn't use issetinside and produces notices. To avoid notices better to use Null Coalescing Operator??which uses issetinside it. Available in PHP 7.

但它不在isset内部使用并产生通知。为了更好地避免通知,最好使用在其中使用的Null Coalescing Operator。在 PHP 7 中可用。??isset

The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise. In particular, this operator does not emit a noticeif the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

Example #5 Assigning a default value

表达式 (expr1) ?? 如果 expr1 为 NULL,则 (expr2) 计算为 expr2,否则为 expr1。特别是,如果左侧值不存在,则此运算符不会发出通知,就像 isset() 一样。这对数组键特别有用。

Example #5 分配默认值

<?php
// 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';
}

?>