PHP quiz #1 - for loopJune 14, 2019
For loops are one of the most fundamental and ubiquitous control flow statements. They are so essential to computer programming, you would expect every developer to know them inside out. As for me, 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
The for loop header
Similarly to other languages, it is perfectly legal to initialize and update multiple variables in for loop headers. Consider the following:
This is a valid PHP code snippet, and it does exactly what you would expect:
it introduces two variables,
with the initial value of
and it increments them by one at the end of each iteration.
No trickery here.
The difficulty lies in the loop's condition:
It might not be immediately obvious what effect does this code have on the loop. One thing's for sure: it won't throw any syntax errors, it's syntactically correct.
Surprising as it may seem,
$i < 3, $j < 2 is actually a
single expression, and as all expressions, it evaluates to something.
Comma operator (C)
In C, the comma operator (
,) is an operator that evaluates two expressions and returns the result of the second one.
For example, the following code prints the text
Hello World! to stdout,
3 to variable
The paranthesized expression is evaluated something like this:
Comma operator (PHP)
This ancient operator did not stand the test of time, not many programming languages support it.
PHP doesn't do either. It's not listed in the precedence table and using it will generally result in a syntax error.
However, surprisingly, there is an exception to the rule: for loop conditions.
For some strange reason, in for loop conditions the comma operator is correctly evaluated.
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 discarded.
The loop will only iterate twice.
This post is part of a series based on a presentation I gave on March 20, 2019.