PHP ternary operator vs null coalescing operator

后端 未结 13 1687
南笙
南笙 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:30

    Both of them behave differently when it comes to dynamic data handling.

    If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

    $a = NULL;
    $c = '';
    
    print $a ?? '1b';
    print "\n";
    
    print $a ?: '2b';
    print "\n";
    
    print $c ?? '1d';
    print "\n";
    
    print $c ?: '2d';
    print "\n";
    
    print $e ?? '1f';
    print "\n";
    
    print $e ?: '2f';
    

    And the output:

    1b
    2b
    
    2d
    1f
    
    Notice: Undefined variable: e in /in/ZBAa1 on line 21
    2f
    

    Link: https://3v4l.org/ZBAa1

提交回复
热议问题