Based on the examples from this page, I have the working and non-working code samples below.
Working code using if
statement:
if (!empty
Note that when using nested conditional operators, you may want to use parenthesis to avoid possible issues!
It looks like PHP doesn't work the same way as at least Javascript or C#.
$score = 15;
$age = 5;
// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));
// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');
The same code in Javascript and C# return "Exceptional" in both cases.
In the 2nd case, what PHP does is (or at least that's what I understand):
$score > 10
? yes$age > 10
? no, so the current $age > 10 ? 'Average' : 'Exceptional'
returns 'Exceptional''Exceptional' ? 'Horrible' : 'Average'
which returns 'Horrible', as 'Exceptional' is truthyFrom the documentation: http://php.net/manual/en/language.operators.comparison.php
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.