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

问题描述 投票:42回答:8

在Python中,可以做到:

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

在PHP中,可以使用三元运算符,如:

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

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

php arrays key default-value
8个回答
44
投票

我刚刚想出了这个小助手功能:

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

每个引用传递一个先前未定义的变量不会导致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

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


45
投票

时间流逝,PHP正在发展。 PHP 7现在支持null coalescing operator??

// 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';

19
投票

Use the error control operator @与三元运算符的PHP 5.3快捷方式版本:

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

7
投票

我觉得创建这样的函数很有用:

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,但您可以将其设置为您需要的任何值。

我希望它有用。


6
投票

PHP 5.3有三元运算符的快捷方式:

$x = $foo ?: 'defaultvaluehere';

这基本上是

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

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


5
投票

一种“略微”的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

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

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

PS:有人可以称之为“内置的==$_=&特殊比较运算符”:

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

PPS:嗯,你显然可以使用

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

但这比==$_=&运营商更糟糕。你知道,人们不太喜欢误差抑制算子。


2
投票

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

$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
)

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


0
投票

a solution proposed by "Marc B"使用三元捷径$x = $foo ?: 'defaultvaluehere';,但它仍然给出通知。可能这是一种错误,也许他的意思是?或者它是在PHP 7发布之前编写的。据Ternary description说:

从PHP 5.3开始,可以省略三元运算符的中间部分。如果expr1 ?: expr3评估为expr1,则表达式expr1返回TRUE,否则返回expr3

但它没有在里面使用isset并产生通知。为了避免通知更好地使用Null Coalescing Operator ??在其中使用isset。提供PHP 7。

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

示例#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';
}

?>
© www.soinside.com 2019 - 2024. All rights reserved.