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

后端 未结 8 1152
庸人自扰
庸人自扰 2020-12-13 08:30

In Python one can do:

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

In PHP one can go for a trinary operator as in:<

8条回答
  •  死守一世寂寞
    2020-12-13 09:01

    PHP 5.3 has a shortcut version of the ternary operator:

    $x = $foo ?: 'defaultvaluehere';
    

    which is basically

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

    Otherwise, no, there's no shorter method.

提交回复
热议问题