n8thanael n8thanael - 2 years ago 110
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.

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download