Bendegúz Csirmaz

PHP quiz #3 - operator associativity

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.

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 answer
A
Syntax 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!

Credits

This post was inspired by Upwork's ridiculously incorrect PHP interview question.

Upwork question


This post is part of a series based on a presentation I gave on March 20, 2019.