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

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

    I find it useful to create a function like so:

    function array_value($array, $key, $default_value = null) {
        return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default_value;
    }
    

    And use it like this:

    $params = array('code' => 7777, 'name' => "Cloud Strife"); 
    
    $code    = array_value($params, 'code');
    $name    = array_value($params, 'name');
    $weapon  = array_value($params, 'weapon', "Buster Sword");
    $materia = array_value($params, 'materia');
    
    echo "{ code: $code, name: $name, weapon: $weapon, materia: $materia }";
    

    The default value in this case is null, but you may set it to whatever you need.

    I hope it is useful.

提交回复
热议问题