The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows:
for (initialization; condition; increment)
code to be executed;
The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:
- The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
- The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
- The update expression increment executes.
- The statements execute, and control returns to step 2.
Have a look at the very simple example that prints out numbers from 0 to 10:
for ($i=0; $i <= 10; $i++)
echo "The number is ".$i."