Home / PHP for loops with multiple statements in each expression

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:

for( expression1a, expression1b; expression2; expression3a, expression3b ) {
    code to run in the loop
}

In my case, I needed to have both a zero based index and a 1 based index inside the loop. A more obvious way to do this with single expressions would be like so:

for( $i = 0; $i < $max; $i++ ) {
     $j = $i + 1;
     // code to run in the loop
}

The alternative way by putting all the assignments into the for( ) part is like this:

for( $i = 0, $j = 1; $i < $max; $i++, $j++ ) {
    // code to run in the loop
}

See also my other post about PHP for loops and counting arrays.