Yesterday while working on one of my projects, I came across a weird scenario: a very simple statement written in PHP was not behaving the way it should.
Below is the simplified version of the code I was working with:
$i = 1; echo $i == 1 ? 'One' : $i == 2 ? 'Two' : 'Three';
At first glance, it is obvious that the output of the above code should be ‘
One‘, but the output here is ‘
After RTFM, I came to know that PHP recommends that we avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious. The above expression will be evaluated as following:
1 2 3 4 5 6 7 8
// a more obvious version of the same code as above $i = 1; echo ($i == 1 ? 'One' : $i == 2) ? 'Two' : 'Three'; // here, you can see that the first expression is // evaluated to 'true', which in turn evaluates to // 'One', thus returning the true branch of the // second ternary expression.
Correct representation that produces the expected result is:
$i = 1; echo $i == 1 ? 'One' : ($i == 2 ? 'Two' : 'Three');
I wonder why developers would leave a feature in the langauge that is ambiguous or not obvious. Has to be a very good reason. But this scenario is a rare one, at least I stumbled across (or noticed) this case for the first time.
Have you come across any other such nuance in PHP?