user3646717 user3646717 - 8 months ago 47
PHP Question

Why does the ternary operator work with print but not with echo in php?

This works:

$number = 1;
$number == 1? print 'yes' : print 'no';

but this doesn't work:

$number = 1;
$number == 1? echo 'yes' : echo 'no';

Why is this happening in PHP?


The parameters to the ternary operator have to be expressions. print 'yes' is an expression, but echo 'yes' is not, because echo is special syntax.

Use the ternary operator as the argument of echo, not the other way around.

echo $number == 1 ? 'yes' : 'no';

It's the same reason you can't write:

$var = echo 'yes';