1

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.

5 Answers 5

4

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";
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the insight.. so it seems like it differs a lot from the regular 'non-shorthand' If statement? if ($a = "abc") "statement" else "statement" vs. shorthand if-statement: statement: $a = "abc" ? "statement" : "statement" --- I guess after reading the documentation I thought they were very similar - but they aren't.
@Robert...this does infact work just fine...thanks: echo isset($a) ? "yes" : "no";
@n8thanael The point is that you can use a regular if statement anywhere you can write a statement, and you can use a ternary expression anywhere you can write an expression.
And the body of an if can be any statement, while the operands of ternary can be any expression.
@pmirnd Yes. An expression can be used wherever a statement is required, but not vice versa.
|
1

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.

Comments

0

The correct way is:

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

Also no need to compare it with true:

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

Comments

0

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

Comments

0

Your last line of code should be like;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.