PHP for loops with multiple statements in each expression

PHP for loops work in the same way as other programming languages and have a useful feature where each expression between the semi-colons can have multiple statements to be executed when separated by a comma. I found this useful myself when I need to have both a zero based and 1 based index in a loop.

PHP for loops

As in other programming languages, PHP for loops work like this:

for( expression1; expression2; expression3 ) {
code to run in the loop
}

where expression1 if executed once at the start of the loop; expression2 determines whether the loop should continue on each iteration; and expression3 is executed at the end of each loop.

Executing multiple statements in each expression

What many people do not realise is that multiple statements can be executed in expression1 and expression3 by separating them with commas. For example in psuedo code: