phpoperators

Ternary operator versus null coalescing operator


How come I can use echo like this:

<?php echo false ? 'yes' : 'no'; ?> //no

But can't use it like this

<?php echo false ?? 'yes'; ?> //nothing output

Solution

  • The ?? Operator in PHP is the Null Coalescing Operator:

    expr1 ?? expr2;
    
    expr1 is returned when expr1 exists and is NOT null; otherwise it returns expr2.
    

    Since in this case expr1 is false but is set, this expression returns Boolean false.

    Compare:

    echo false ?? 'It is FALSE'; // won't be displayed
    echo null ?? 'it is NULL'; // It will work
    

    Echo does not output when passed Boolean false.