user3646717
user3646717

Reputation: 1095

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?

Upvotes: 1

Views: 931

Answers (2)

Barmar
Barmar

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

Jonathan M
Jonathan M

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

Related Questions