PHP – For Loop

Posted on May 3, 2011

0


The for loop is simply a while loop with a bit more code added to it. The common tasks that are covered by a for loop are:
Set a counter variable to some initial value.
Check to see if the conditional statement is true.
Execute the code within the loop.
Increment a counter at the end of each iteration through the loop.

The for loop allows you to define these steps in one easy line of code. It may seem to have a strange form, so pay close attention to the syntax used!
For Loop Example

Let us take the example from the while loop lesson and see how it could be done in a for loop. The basic structure of the for loop is as follows:
Pseudo PHP Code:

for ( initialize a counter; conditional statement; increment a counter){
do this code;
}

Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated by a semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is needed because these are separate expressions. However, notice that a semicolon is not needed after the “increment counter” expression.

Here is the example of the brush prices done with a for loop .
PHP Code:

$brush_price = 5;

echo “

“;
echo “

“;
echo “

“;
for ( $counter = 10; $counter <= 100; $counter += 10) {
echo "

“;
}
echo “

Quantity Price
“;
echo $counter;
echo “
“;
echo $brush_price * $counter;
echo “

“;

Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500

It is important to note that both the for loop and while loop implementation of the price chart table are both OK at getting the job done. However, the for loop is somewhat more compact and would be preferable in this situation. In later lessons we will see where the while loop should be used instead of the for loop.

Advertisements
Posted in: PHP