PHP quiz #3 - operator associativity
June 16, 2019Operators 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.
Question
What will this code output?
-
A
Syntax error
-
B
true
-
C
false
Answer
Show the answerSyntax error
Explanation
Operator associativity
Operator associativity decides how operators of equal precedence are grouped.
operator | associativity | example | result |
---|---|---|---|
+ (addition) |
left | 1 + 2 + 3 |
(1 + 2) + 3 |
= (assignment) |
right | $a = $b = $c |
$a = ($b = $c) |
Non-associative operators
In PHP, however, comparison operators are non-associative. They cannot be used next to each other.
The expression $z > $y > $x
is illegal.
operator | associativity | example | result |
---|---|---|---|
> (greater-than) |
non-associative | $z > $y > $x |
syntax error |
Other languages
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:
Awesome!
Credits
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