Thread: Looping in PHP
View Single Post
Banned
25Jul2011,14:39  
ankitasharma's Avatar
The common tasks that are covered by a for loop are:

1. Set a counter variable to some initial value.
2. Check to see if the conditional statement is true.
3. Execute the code within the loop.
4. 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!

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.