PHP ternary operator syntax error

Mattis
<?
$percent = 105;
$percent = ($percent > 100) ? 100 :
           ($percent < 0) ? 0 : $percent;
echo $percent;
?>

Why does this echo 0? I'm looking at JavaScript code I've written that work and find no difference in logic.

Jon

In PHP, in contrast to JS and many other languages, the ternary operator is left-associative. This means your expression is equivalent to

$percent = (($percent > 100) ? 100 : ($percent < 0)) ? 0 : $percent;

And since ($percent > 100) ? 100 : ($percent < 0) evaluates to 100 in this case, it's as if you had written

$percent = 100 ? 0 : $percent;

Which obviously results in zero.

A suggestion: Never write complex expressions without parentheses. Putting parens at the appropriate places would make the code work in both JS and PHP, and arguably also make it easier to read. In the same spirit, I have promised myself to never use more than a single ternary in the same expression. You might want to do the same.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related