Troubleshooting "Unexpected T_Echo" in Ternary Operator Statement

Troubleshooting Unexpected T_ECHO in ternary operator statement

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.

PHP ternary operator giving an unexpected T_echo

you should write like this:

echo (isset($tag) ? '<a href="#">' . $tag['firstname'] . '</a>' : '');

Why does the ternary operator work with print but not with echo in php?

The parameters to the ternary operator have to be expressions. print 'yes' is an expression, but echo 'yes' is not, because echo is special syntax.

Use the ternary operator as the argument of echo, not the other way around.

echo $number == 1 ? 'yes' : 'no';

It's the same reason you can't write:

$var = echo 'yes';

PHP ternary operator expecting colon and semicolon

Try this:

<?php echo $columnCasecheck === true ? '-3' : '-4'; ?>

Inside the ternary you should put value or expression, instead of commands.

So the echo should be outside the ternary expression.

Also, if you don't need strict comparison, you can just write:

<?php echo $columnCasecheck ? '-3' : '-4'; ?>

So your whole line will be:

<div class="col-sm<?php echo $columnCasecheck ? '-3' : '-4'; ?>">

Issue with isset() inside nested ternary operator

I'm not sure, but I think it should be

echo (isset($_COOKIE['m_name'])? $_COOKIE['m_name']: (isset($this->userdata)?$this->userdata[0]->first_name:'No Value'));

Issue with isset() inside nested ternary operator

I'm not sure, but I think it should be

echo (isset($_COOKIE['m_name'])? $_COOKIE['m_name']: (isset($this->userdata)?$this->userdata[0]->first_name:'No Value'));

php / apache2 - shorthand if (bug - discussion, finding an explanation)

Okay, my fault - I should have read the manual on ternary operators before using them "out of my head"...

I changed the operator to the correct format as Acyclic Tau and MTilsted mentioned in the comments:

$output .= ($row[1] ? $row[1] : $row[0]);

The strange speed issue is gone - but the next question is why PHP is not throwing an exception because of the wrong syntax?

Is it mandatory to enclose an entire ternary operator statement in parenthesis in this statement?

The original intent was readability I guess or maybe the developer was just following a Coding Standard. Though wrapping and indenting would help on readability way more than adding unnecessary parenthesis. Like this for exmaple:

$class = is_array($tagClasses)
? 'class="' . implode(" ", $tagClasses) . '"'
: '';

When you definitely want to add () around a ternary operator is when you are nesting one to another (which is not nice anyway), or you can put the operands of the operator between () for the sake of readability if you have complex expressions there.



Related Topics



Leave a reply



Submit