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

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

    I just came up with this little helper function:

    function get(&$var, $default=null) {
        return isset($var) ? $var : $default;
    }
    

    Not only does this work for dictionaries, but for all kind of variables:

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

    Passing a previously undefined variable per reference doesn't cause a NOTICE error. Instead, passing $var by reference will define it and set it to null. The default value will also be returned if the passed variable is null. Also note the implicitly generated array in the spam/eggs example:

    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
    

    Note that even though $var is passed by reference, the result of get($var) will be a copy of $var, not a reference. I hope this helps!

提交回复
热议问题