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

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

    Time passes and PHP is evolving. PHP 7 now supports the null coalescing operator, ??:

    // Fetches the value of $_GET['user'] and returns 'nobody'
    // if it does not exist.
    $username = $_GET['user'] ?? 'nobody';
    // This is equivalent to:
    $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
    
    // Coalescing can be chained: this will return the first
    // defined value out of $_GET['user'], $_POST['user'], and
    // 'nobody'.
    $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
    

提交回复
热议问题