PHP Tutorial - PHP for loop






A for loop is made up of a declaration, a condition, and an action:

  • declaration defines a loop-counter variable and sets it to a starting value;
  • condition checks the loop-counter variable against a value;
  • action changes the loop counter.




Syntax

The general syntax of a for loop is as follows:

   
for ( declaration; condition; action ) { 
  // Run this code  
} 
// More code here    

Example 1

Here is how a for loop looks in PHP:


<?php
        for ($i = 1; $i < 10; $i++) {
                print "Number $i\n";
        }
?>

The code above generates the following result.

As you can see, the for loop has the three parts separated by semicolons. In the declaration, we set the variable $i to 1.

For the condition, we have the loop execute if $i is less than 10.

Finally, for the action, we add 1 to the value of $i for every loop iteration.





Example 2

The following example has an infinite loop.

<?php
        for (;;) {
                print "In loop!\n";
        }
?>

Example 3

You can nest loops as you see fit, like this:


<?php
     for ($i = 1; $i < 3; $i = $i + 1) {
             for ($j = 1; $j < 3; $j = $j + 1) {
                     for ($k = 1; $k < 3; $k = $k + 1) {
                             print "I: $i, J: $j, K: $k\n";
                     }
             }
     }
?>

The code above generates the following result.