This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.
PHP quiz #1 - for loop conditionsJune 14, 2019
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?
0,0 1,1 2,2
0,0 1,1 2,1
AnswerShow the answer
First of all, I'd like to clarify that it is perfectly legal to initialize and update multiple variables in for statements.
The question actually refers to the loop's condition.
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?
In C, the comma operator is an operator that evaluates two expressions and returns the result of the second one.
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.
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!
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.