Reputation: 1095
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?
Upvotes: 1
Views: 931
Reputation: 781834
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';
Upvotes: 1
Reputation: 17451
Check your log for a warning. The ternary operator must return a value. print
returns 1
always, but echo
does not return a value.
Regarding your comment about putting echo
in a function, functions that don't explicitly return a value return null
by default, therefore, the function is indeed returning a value:
http://php.net/manual/en/functions.returning-values.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
http://php.net/manual/en/function.print.php
http://php.net/manual/en/function.echo.php
Upvotes: 0