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

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

    If you enumerate the default values by key in an array, it can be done this way:

    $foo = array('a' => 1, 'b' => 2);
    $defaults = array('b' => 55, 'c' => 44);
    
    $foo = array_merge($defaults, $foo);
    
    print_r($foo);
    

    Which results in:

    Array
    (
        [b] => 2
        [c] => 44
        [a] => 1
    )
    

    The more key/value pairs that you enumerate defaults for, the better the code-golf becomes.

提交回复
热议问题