Home > Enterprise >  Why does the PHP ternary operator does not work here?
Why does the PHP ternary operator does not work here?

Time:02-02

This works well upon receiving an array of data (i.e. $lignes), suspendu being a boolean:

foreach ($lignes as $ligne)
{
 //…
 if ($ligne['suspendu'])
   echo "<td style='".$styleSuspendu."'>".$ligne['pseudo']."</td>";
 else
   echo "<td>".$ligne['pseudo']."</td>";
//…
}

While the following does not:

$ligne['suspendu'] ? echo "<td style='".$styleSuspendu."'>".$ligne['pseudo']."</td>";
                   : echo "<td>".$ligne['pseudo']."</td>";

I have also tried to encompass statements whithin {} or (), to no avail.

What is wrong with my using the ternary operator here?

CodePudding user response:

Because echo doesn't return a value, and you can't put a language construct or a full statement like that inside the ternary's second and third sections. They have to be expressions which evaluate to a returnable value - e.g. something you can assign to a variable (or pass to an echo command).

Also you can't have a semi-colon after the first possible returnable expression - the line / statement is not being terminated there.

So just make the ternary return the string value, and then echo that later if you need to. One possible version:

$result =  ($ligne['suspendu'] ? "<td style='".$styleSuspendu."'>".$ligne['pseudo']."</td>" : "<td>".$ligne['pseudo']."</td>");
echo $result;

If you don't need the variable and just want to echo it immediately, and don't find the parentheses useful for readabilty, then you can of course shorten it to:

echo $ligne['suspendu'] ? "<td style='".$styleSuspendu."'>".$ligne['pseudo']."</td>" : "<td>".$ligne['pseudo']."</td>";

And/or if you want to remove the duplication of certain elements of the output content (e.g. the HTML td tags and the variable in the middle), you could go with something like:

echo "<td".($ligne['suspendu'] ? "style='".$styleSuspendu."'" : "").">".$ligne['pseudo']."</td>"";

Documentation:

CodePudding user response:

It does not work, as you are using echo in the branches, which is not part of the ternary operator. This might work:

echo $ligne['suspendu'] ? "<td style='".$styleSuspendu."'>".$ligne['pseudo']."</td>";
                   : "<td>".$ligne['pseudo']."</td>";

In any case: this code is pretty hard to read, and using this codestyle makes it even worse compared to the former code. You should use a proper templating engine that helps you to seperate the markup from the PHP code

  •  Tags:  
  • Related