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

后端 未结 8 1167
庸人自扰
庸人自扰 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 08:56

    A "slightly" hacky way to do it:

    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:

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

    PPS: Well, you could obviously just use

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

提交回复
热议问题