PHP - Using the for Statement

Introduction

You can use a for loop when you know how many times you want to repeat the loop.

You use a counter variable within the for loop to keep track of how many times you've looped.

The general syntax of a for loop is as follows:


for ( expression1; expression2; expression3 ) {
   // Run this code
}
// More code here

If you only need one line of code in the body of the loop you can omit the braces.

Here's a typical example of a for loop in action.

This script counts from 1 to 10, displaying the current counter value each time through the loop:

for ( $i = 1; $i  <= 10; $i++ ) {
    echo "I've counted to: $i \n ";
}
echo "All done!";

The loop sets up a new counter variable, $i , and sets its value to 1.

The code within the loop displays the current counter value.

Each time the loop repeats, $i is incremented.

Here's the previous for loop rewritten using while :

Demo

<?php
         $i = 1;/*from w  w w  .j  av a 2 s.c o m*/

         while ( $i  <= 10 ) {
           echo "I've counted to: $i \n ";
           $i++;
         }

         echo "All done!";
?>

Result

Related Topic