n8thanael
n8thanael

Reputation: 400

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');

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

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

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

Thank you for your consideration.

Upvotes: 1

Views: 653

Answers (5)

Barmar
Barmar

Reputation: 782407

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";

Upvotes: 4

Amous
Amous

Reputation: 514

Rewrite the statement as,

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

The ternary operator doesn't exactly function like an if statement. The ternary operator does not execute the 2nd or 3rd expressions, it returns it.

Upvotes: 1

merdincz
merdincz

Reputation: 448

Your last line of code should be like;

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

Upvotes: 0

Robert
Robert

Reputation: 20286

Because when you use ternary operators you need to count operators precedence and associativity

you can rewrite your code to

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

Upvotes: 0

kay27
kay27

Reputation: 909

The correct way is:

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

Also no need to compare it with true:

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

Upvotes: 0

Related Questions