n8thanael n8thanael - 6 months ago 3
PHP Question

PHP Ternary operator ('shorthand' if-statement)

I've reviewed the PHP Manual here: #3 ternary operators

but I don't understand why all three of these don't function as expected:

$a = array('a','b','c');

if(isset($a)){echo "yes";} else {echo "no";}

isset($a) == true ? $answer = "yes" : $answer = "no";
echo $answer;

//does not work
isset($a) == true ? echo "yes" : echo "no";

Thank you for your consideration.


Since the ternary expression is an expression, its operands have to be expressions as well. echo is not an expression, it's a statement, it can't be used where expressions are required. So the last one doesn't work for the same reason you can't write:

$a = echo "abc";