PHP ternary operator vs null coalescing operator

后端 未结 13 1703
南笙
南笙 2020-11-22 15:58

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave d

相关标签:
13条回答
  • 2020-11-22 16:49

    If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

    $val = $_GET['username'] ?: 'default';
    

    So instead you have to do something like this:

    $val = isset($_GET['username']) ? $_GET['username'] : 'default';
    

    The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

    $val = $_GET['username'] ?? 'default';
    

    Note that it does not check truthiness. It checks only if it is set and not null.

    You can also do this, and the first defined (set and not null) value will be returned:

    $val = $input1 ?? $input2 ?? $input3 ?? 'default';
    

    Now that is a proper coalescing operator.

    0 讨论(0)
提交回复
热议问题