for in PHP with examples

The "for" loop in PHP is used when we need to execute some block of code multiple times.

PHP for loop syntax

The syntax of the "for" loop in PHP is:

for(initialize; condition; update)
{
   // body of the loop;
}

The execution of the for loop starts with initialize. This statement executes at the start of the loop and only executes once. This is used to initialize the loop variable, for example: $x = 1;

Before entering the body of the loop, the condition expression must be evaluated to be true.

If the condition is evaluated to be true, then the "// body of the loop;" will be executed.

After executing the "// body of the loop;", the program flow goes to update part of the loop to update the loop variable.

After updating the loop variable, the condition gets evaluated; as already mentioned, before entering the loop, the condition's expression must be evaluated to true. This process continues until the condition is evaluated as false.

PHP for loop example

Consider the following PHP code as an example demonstrating the practical use of the "for" loop.

<?php
   for($x=1; $x<=10; $x++)
      echo $x, "<BR>";
?>

The output is:

php for loop

The number of times the block of code inside the loop will be executed depends upon how many times the condition of the loop evaluates to be true. In the above example, since the condition $x<=10; evaluates to be true ten times, the statement echo $x, "<BR>"; has been executed ten times.

The above program can also be written as:

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

Here is another example of a for loop along with its output and in-depth description:

<?php
   for($num=3; $num<=30; $num=$num+3)
   {
      echo $num;
      echo "<BR>";
   }
?>

The output produced by the above PHP example on the for loop is shown in the snapshot given below:

for loop in php

The dry run of the above example is:

You can also use multiple initialize, update, and/or condition statements. For example, in the following example, I'm going to use two initialization codes for the initialize part of the loop:

<?php
   for($num=4, $i=1; $i<=10; $i++)
      echo "$num * $i = ", $num*$i, "<BR>";
?>

The output of this example is shown in the snapshot given below:

for loop example in php

Note: When using multiple conditional statements for a condition, the execution of the loop stops when any of the conditional statements evaluates to be false.

Advantages of the for loop in PHP

Disadvantages of the for loop in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!