This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.
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?
<?php
$x = 2;
$y = 4;
$z = 6;
if ($z > $y > $x) {
echo 'true';
} else {
echo 'false';
}
-
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.
x = 2
y = 4
z = 6
if z > y > x:
print('true')
else:
print('false')
# true
Awesome!
Conclusion
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).