for
The for loop is possibly the most customizable of loops in PHP. In addition to the block of code it loops through, there are three sections of code declared.
1) The set up: the code that’s executed once before the first loop starts.
2) The condition: Executed at the start of each loop (including the first one). If this evaluates to true, we go into the loop.
3) The other: This third piece is executed at the end of each loop. It can do whatever you like it to.
Here’s a typical use. We initialize a variable, keep looping as long as that variable is below a certain value, and we increment the variable by one after each loop.
for( $i = 1; $i <= 5; $i++ ) { echo "$i\n"; } echo 'done'; /* 1 2 3 4 5 done */
Each of the three parts can have as many statements as you wish - just separate them with commas. Here we work with two variables but are keeping the same condition as last time.
for( $i = 1, $j = 7; $i <= 5; $i++, $j-- ) { echo "$i * $j = " . ($i * $j) . "\n"; } echo 'done'; /* 1 * 7 = 7 2 * 6 = 12 3 * 5 = 15 4 * 4 = 16 5 * 3 = 15 done */
The second part is a little different when it comes to having multiple statements in it. We think of it as the condition when in reality it can be any code you wish to execute before each loop. The last statement in it will act as the condition.
See how that works out in the following. The condition for $j is always false in this example but that has no affect on the loop since only the last statement ($i <= 5) tells the loop when to stop.
for( $i = 1, $j = 7; $j > 20, $i <= 5; $i++, $j-- ) { echo "$i * $j = " . ($i * $j) . "\n"; } echo 'done'; /* 1 * 7 = 7 2 * 6 = 12 3 * 5 = 15 4 * 4 = 16 5 * 3 = 15 done */
Here we multiply $j by two at the start of each loop (while still decreasing it my one at the end of each loop). You can put just about anything there.
for( $i = 1, $j = 7; $j *= 2, $i <= 5; $i++, $j-- ) { echo "$i * $j = " . ($i * $j) . "\n"; } echo 'done'; /* 1 * 14 = 14 2 * 26 = 52 3 * 50 = 150 4 * 98 = 392 5 * 194 = 970 done */
Any (or all) of the three parts can be left out as well. Just put the semicolon in to separate the parts. Here we leave out the condition but place one inside the loop so we don’t have an endless loop.
Note the use of break. continue also works in a for loop.
for( $i = 1; ; $i++ ) { echo "$i\n"; if( $i >= 5 ) { break; } } echo 'done'; /* 1 2 3 4 5 done */
One more note. You can also use the alternative syntax colon/endfor; instead of the curly braces here.
for( $i = 1; $i <= 5; $i++ ) : echo "$i\n"; endfor; echo 'done'; /* 1 2 3 4 5 done */
