This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.
PHP quiz #3 - operator associativityJune 16, 2019
Operators are the building blocks of computer programs. You might think you know them, but the devil is in the details. After all these years, I still find myself revisiting the precedence table every once in a while.
What will this code output?
AnswerShow the answer
Operator associativity decides how operators of equal precedence are grouped.
In PHP, however, comparison operators are non-associative. They cannot be used next to each other.
$z > $y > $x is illegal.
Most programming languages do not allow the chaining of relational operators.
The desired result is usually achieved with something like
$z > $y && $y > $x.
A notable exception is Python. It evaluates chained relational operators the way someone less scarred by programming would expect.
There is a reason why you've never seen comparison operators chained like this in PHP code. It's because it's not legal.
Exam questions often try to trick you like this. When I notice something fishy and the problem isn't completely obvious, as a rule of thumb, I always consider the 'syntax error' answers first. Trust your intuition!
This post was inspired by Upwork's incorrect PHP interview questions (question #10).