The PHP For Loop

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:

Syntax : 
        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 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:


<?php
for ($i=0; $i <= 10; $i++)
     {
   echo "The number is ".$i."<br />";
     }
?>

Comments