Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubleshooting "Unexpected T_ECHO" in ternary operator statement

Tags:

($DAO->get_num_rows() == 1) ? echo("is") : echo("are");

This dose not seem to be working for me as intended, I get an error "Unexpected T_ECHO". I am expecting it to echo either 'is' or 'are'.

I have tried it without the brackets around the conditional. Am I just not able to use a ternary operator in this way?

The $DAO->get_num_rows() returns an integer value.

like image 394
thecoshman Avatar asked Apr 23 '10 12:04

thecoshman


3 Answers

The Ternary operator is not identical to an if-then. You should have written it

echo ($DAO->get_num_rows() == 1) ? "is" : "are";

It returns the value in the 2nd or 3rd position. It does NOT execute the statement in the 2nd or 3rd position.

like image 160
MJB Avatar answered Sep 28 '22 07:09

MJB


The ternary operator should result in a value -- and not echo it.


Here, you probably want this :

echo ($DAO->get_num_rows() == 1) ? "is" : "are";


If you want to use two echo, you'll have to work with an if/else block :

if ($DAO->get_num_rows() == 1) {
    echo "is";
} else {
    echo "are"
}

Which will do the same thing as the first portion of code using the ternary operator -- except it's a bit longer.

like image 45
Pascal MARTIN Avatar answered Sep 28 '22 07:09

Pascal MARTIN


The ternary operator returns one of two values after evaluating the conditions. It is not supposed to be used the way you are using it.

This should work:

echo ($DAO->get_num_rows() == 1 ? "is" : "are");
like image 38
Pekka Avatar answered Sep 28 '22 07:09

Pekka