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

后端 未结 8 1145
庸人自扰
庸人自扰 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

    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:

    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

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

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

    Example #5 Assigning a default value

    
    

提交回复
热议问题