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

后端 未结 8 1117
庸人自扰
庸人自扰 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 09:01

    PHP 5.3 has a shortcut version of the ternary operator:

    $x = $foo ?: 'defaultvaluehere';
    

    which is basically

    if (isset($foo)) {
       $x = $foo;
    else {
       $x = 'defaultvaluehere';
    }
    

    Otherwise, no, there's no shorter method.

    0 讨论(0)
  • 2020-12-13 09:01

    There was a solution proposed by "Marc B" to use ternary shortcut $x = $foo ?: 'defaultvaluehere'; but it still gives notices. Probably it's a mistyping, maybe he meant ?? or it were written before PHP 7 release. According to Ternary description:

    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

    But it doesn't use isset inside and produces notices. To avoid notices better to use Null Coalescing Operator ?? which uses isset inside it. Available in PHP 7.

    The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise. In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

    Example #5 Assigning a default value

    <?php
    // Example usage for: Null Coalesce Operator
    $action = $_POST['action'] ?? 'default';
    
    // The above is identical to this if/else statement
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
    } else {
        $action = 'default';
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题