PHP Tricky Ternary Operators

69 / 100
PHP Logo

PHP is indeed a simple language one can learn over the months or even weeks or even days. As a programmer, we will know about writing if…else statements that will check if the condition is met. What about ternary operators in PHP?

Here is an example

$term = 69;
if ($term > 20) $term = 20;
elseif ($term < 10) $term = 10;
echo $term;
The answer should be 20.

Instead of writing codes as long as the above why not write it in ternary form. All it requires is usually 1 line for the code above.
Now how would you do that in ternary form?

$term = 69;
$term = $term > 20 ? 20 : $term < 10 ? 10 : $term;
echo $term;

The codes should work well, but… it looks like that there is something wrong over here.

It shows the answer as 10.

The proper one should be the one below. The above was actually some calculations for a code and the answer was not what was wanted. The below is how the solution should be.

$term = 69;
$term = $term > 20 ? 20 : ($term < 10 ? 10 : $term);
echo $term;
The answer should now be 20.

Finally just by closing one part of the code, the code is now showing the result it should be. Pretty simple there.

Leave a Reply