PHP for loop

Description

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  //from w w w  .  j  a  va2s .  c o m
} 
// More code here    

Example 1

Here is how a for loop looks in PHP:


<?php/*from w  w w.  j  av a  2s .com*/
        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/*from   w ww.  java  2 s  . c o m*/
        for (;;) {
                print "In loop!\n";
        }
?>

Example 3

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


<?php/*w ww .  j a v a  2 s  .  c  om*/
     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.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition