login

PHP For Statement

PHP for statement is the most complex loop statement in PHP. You can use for statement to execute a code block in a specific or unspecific times based on conditions. Here is the form of the for statement.

<?php

     for(expression1; expression2; expression3){
         // code block to be executed.
     }
?>

The rules of each expression in for statement above are as follows:

  • Expression1 is always evaluated at the first iteration by default.
  • Expression2 is evaluated at the beginning of each iteration. This expression is used to control whether the looping will continue or not.
  • Expression3 is evaluated at the end of each iteration.
  • Any expression can be empty.

Let's take a look at several examples of using for loop.

First example demonstrate three expressions which are empty.

<?php
     $i = 1;
     for(;;){
        echo $i++;
        if ($i == 10)
          break;
     }
?>

In this example, for loop statement is used similar to while and do while statement with condition is always true.

The second example demonstrates three expressions are in place.

<?php
     for($i = 1;$i <= 10;$i++){
        echo $i;
     }
?>

This example behaves similarly as the first example. First it initializes variable $i with the value 1. Then we check if $i less than or equal 10 or not, if not it outputs the value of $i and then increase $i by 1.

PHP also supports "colon syntax" for for statement.

 <?php
     for(expression1;expression2;expression3):
        // code block to be executed
     endfor;
?>

for statement again can be nested within another for statement. Here is an example of using nested for statement to sort an array by using bubble sort algorithm. You will learn about array in later tutorial. The code just demonstrates the idea.

<?php
 // example of using for statement in sorting algorithm
 function BubbleSort( &$lst ) {
     $tmp = ""; // for storing temporary value
     $length = count( $lst ); 
     for( $i = 0; $i < $length-1; $i++ ) {
         for( $j = 0; $j < $length - 1 - $i; $j++ ) {
             if( $lst[$j+1] < $lst[$j] ) {
                 $tmp = $lst[$j];
                 $lst[$j] = $lst[$j+1];
                 $lst[$j+1] = $tmp;
             }
         }
     }
 }
 ?>