0
<?
$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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, there you go. Thank you Jon Snow! Will accept this when the lockout is lifted.
Read PHP: A fractal of bad design and discover many more gems like this.
2

Your code prints 0 due to operator priorities.

This one works fine:

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

Comments

1

this is what you want:

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

Or maybe a bit simpler, like this:

$percent = min(100, max(0, $percent));

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.