RSS

For Loop

Sat, Jan 16, 2010

PHP & MySql

Then we’ve got the for loop. This loop is in some point of view kind of smilar to the while loop as it as well repeats a certain code several times. Though, the for loop requires a variable to be set, an increment value (or decrement) and a condition, as argruments of the loop. A basic example of a for loop looks like this (structure) :

for ( set variable; condition; action increment/decrement ) {

            ...act code...

}

Say we want to set a begin value (we use the variable named $i, which is a common name for integer variables to be used) to 0 and we want to let it count to 10.

Example:

for ( $i = 0; $i <= 10; $i++ ) {

            echo $i;

}

The variable set is $i, which we set to 0. The condition for the code to be ran is that $i is smaller than or equal to 10. So as long as this is the case, the value of $i will be shown on the screen (echo $i). Each time it shows $i on the screen, $i will be increased by 1 ($i++) and the loop will be repeated as long as the condition ($i<=10) is still true. In other words: it shows the value of $i on the screen, increases it by 1, shows it on the screen again, etc., and repeats this until $i is equal to 10.

Output:

1
2
3
4
5
6
7
8
9
10

You could also make it count downwards:

for ( $i = 10; $i => 0; $i--) {

            echo $i;

}

You see we now set $i (begin value) to 10 and set the condition to $i is larger or equal to 0, and the action to repeat each time the loop is executed to $i--(which means: decrease $i by 1).

Admin.