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

Yau*_*ich 46 php arrays key default-value

Python中,可以做到:

foo = {}
assert foo.get('bar', 'baz') == 'baz'
Run Code Online (Sandbox Code Playgroud)

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

$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz');
Run Code Online (Sandbox Code Playgroud)

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

Iva*_*ych 47

时间流逝,PHP正在发展.PHP7现在支持Null合并运算符:

// 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';
Run Code Online (Sandbox Code Playgroud)


ste*_*uel 44

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

function get(&$var, $default=null) {
    return isset($var) ? $var : $default;
}
Run Code Online (Sandbox Code Playgroud)

这不仅适用于字典,而且适用于所有类型的变量:

$test = array('foo'=>'bar');
get($test['foo'],'nope'); // bar
get($test['baz'],'nope'); // nope
get($test['spam']['eggs'],'nope'); // nope
get($undefined,'nope'); // nope
Run Code Online (Sandbox Code Playgroud)

传递每个引用的先前未定义的变量不会导致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
Run Code Online (Sandbox Code Playgroud)

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

  • 凉.我想知道为什么这仍然不是PHP?:) (4认同)
  • 有没有办法删除/取消设置`$ ar [0] [1] [1]```get($ ar [0] [1] [1]),'def');`? (3认同)
  • 更好地使用`!empty`而不是`isset`,它验证变量是否实际具有值. (2认同)

rom*_*nlv 21

使用错误控制operator @ with PHP 5.3快捷版本的三元运算符

@

  • 请注意,所有这些都是在评估`$ foo ['bar']`时暂时设置`error_reporting(0)`.它仍将调用错误处理程序,如果`error_reporting()=== 0`,则错误处理程序负责忽略错误. (4认同)
  • 不适用于像`0`这样的值。`$foo = ['bar' => 0]; $bar = @$foo['bar'] ?: 'defaultvalue';` 给出“defaultvalue”。 (2认同)

rbe*_*nto 8

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

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

并像这样使用它:

$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 }";
Run Code Online (Sandbox Code Playgroud)

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

我希望它有用.


Mar*_*c B 5

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

$x = $foo ?: 'defaultvaluehere';
Run Code Online (Sandbox Code Playgroud)

这基本上是

if (isset($foo)) {
   $x = $foo;
else {
   $x = 'defaultvaluehere';
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这不起作用.当变量未定义时,短三元句法仍会生成"NOTICE"错误,这与`isset`函数不同. (22认同)
  • 是的,这行不通。三元运算符不提供隐式 isset() 调用 (2认同)

Nik*_*kiC 5

一种"略微"的hacky方式:

<?php
    $foo = array();
    var_dump('baz' == $tmp = &$foo['bar']);
    $foo['bar'] = 'baz';
    var_dump('baz' == $tmp = &$foo['bar']);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

<?php
    var_dump('baz' ==$_=& $foo['bar']);
Run Code Online (Sandbox Code Playgroud)

PPS:嗯,你显然可以使用

<?php
    var_dump('baz' == @$foo['bar']);
Run Code Online (Sandbox Code Playgroud)

但这比==$_=&操作员更糟糕.你知道,人们不太喜欢误差抑制算子.