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:
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:
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:
The alternative way by putting all the assignments into the for( ) part is like this:
See also my other post about PHP for loops and counting arrays.
0 comments:
Post a Comment