Bendegúz Csirmaz

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

PHP quiz #1 - for loop conditions

For loops: one of the most fundamental and ubiquitous control flow statements. I never would have thought I could learn anything new about them. I was wrong.


What will this code output?


for ($i = 0, $j = 0; $i < 3, $j < 2; ++$i, ++$j) {
  echo "$i,$j\n";
  • A
    Syntax error
  • B
  • C
  • D


Show the answer


First of all, I'd like to clarify that it is perfectly legal to initialize and update multiple variables in for statements.

for ($i = 0, $j = 0; ...; ++$i, ++$j) // OK

The question actually refers to the loop's condition.

for (...; $i < 3, $j < 2; ...) // ?

At first glance, it might seem like multiple conditions are being defined. This is not the case. $i < 3, $j < 2 is a single expression. The question is, what does it evaluate to?

Comma operator

In C, the comma operator is an operator that evaluates two expressions and returns the result of the second one.

/* prints "Hello World!” and assigns 3 to 'a' */
int a = (printf("Hello World!\n"), 1 + 2);

Comma operator in PHP

This ancient operator did not stand the test of time. Not many programming languages support it.

There is no comma operator in PHP either. It is not listed in the precedence table and using it will generally result in a syntax error.


// Parse error: syntax error, unexpected ',' in ...
$a = (1, 2);

For loop conditions

However, there is an exception to the rule: for loop conditions.

For some strange reason, in for loop conditions the comma operator is correctly evaluated. Weird!

for (...; $i < 3, $j < 2; ...)
for (...; $j < 2; ...)

In this case, the expression $i < 3, $j < 2 has the same effect as $j < 2. The first operand is evaluated, but its result is disregarded.

The loop will only iterate twice.


PHP is an exceptional language. Literally: it has a lot of exceptions and weird rules, comma operators in for loop conditions being one of them.

Fortunately, there are not many great uses of this operator - not even in other languages. In fact, it's better if you just forget it.

If you happen to know the rationale behind adding this feature to PHP, please let me know in the comments below.

In the next post we will continue looking at weird commas, but in a different context.

next >>