Skip to content
Advertisement

Using ternary operator in echo?

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement