PHP for loop

In this chapter you will learn:

  1. What is for loop
  2. for loop Syntax
  3. Example - for loop with
  4. Example - Infinite Loops
  5. Example - Loops Within Loops

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  /*  j av a 2 s .  c o  m*/
} 
// More code here    

Example 1

Here is how a for loop looks in PHP:


<?php//from  j a  v  a  2  s.co  m
        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 jav  a 2  s  .com
        for (;;) {
                print "In loop!\n";
        }
?>

Example 3

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


<?php/*from j av a 2s.  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.

Next chapter...

What you will learn in the next chapter:

  1. What is a break statement
  2. Syntax for break statement
  3. Example - exit a for loop with break statement
  4. Example - Exit only one level of loop
  5. Example - exit more than one level with break statement
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require