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:
This post was inspired by Upwork's ridiculously incorrect PHP interview question.
This post is part of a series based on a presentation I gave on March 20, 2019.
- PHP quiz #1 - for loop
- PHP quiz #2 - echo
- PHP quiz #3 - operator associativity
- PHP quiz #4 - hoisting
- PHP quiz #5 - constructor overriding
- PHP quiz #6 - covariance