PHP for Loop

In this lesson, you will learn about the for Loop in PHP, Nested for Loops, and their usages, along with examples to better understand the topics.


PHP For Loop

Use the PHP for loop to iterate over a set of codes a predetermined number of times. It indicates that the for loop is used when the number of times you want to run a block of code is already known.

Note
If the number of iterations is unknown, a while loop should be used.

Basic Syntax of for Loop

<?php
for (initialize; condition; increment){
//code to be processed here
}
?>
§ "For...{...}" is generally an integer loop block; it is used to set the original value of the counter.
§ "Condition" means the condition assessed for each execution of PHP. If it is valid, then execution of the for 'loop'. The program will exit the 'loop' to the next statement if it assesses as false.
§ "Increment" is used to increase the counter integer's original value.

for Loop Flowchart 

 

Example

<?php
echo "PHP ***For loop*** Example";
echo "<br>";
echo " ------------For loop ------------------ ";
echo "<br>";

echo "The table of 2 ";
echo "<br>";
for ($var = 1;$var <= 10;$var++)
{
    $evennumber = 2 * $var;
    echo "2 * $var is $evennumber <br/>";
}

Output

PHP ***For loop*** Example
------------For loop ------------------
The table of 2
2 * 1 is 2
2 * 2 is 4
2 * 3 is 6
2 * 4 is 8
2 * 5 is 10
2 * 6 is 12
2 * 7 is 14
2 * 8 is 16
2 * 9 is 18
2 * 10 is 20

PHP Nested For Loop Statement

In PHP, we can use a loop inside a loop. This is what we call loop nesting. A nested loop is fully executed for one outer loop in the case of an inner or nested loop. If the outer loop is executed four times and the inner loop two times, the inner loop will be executed eight times (4 X 2).

Example

<?php
echo "PHP ***Nested For loop *** Example";
echo "<br>";
echo " ------------Nested For loop ------------------ ";
echo "<br>";
$var = 1;
for ($var;$var <= 4;$var++)
{
    echo 'Outer Loop ' . "$var" . " times <br/>";
    for ($var2 = 1;$var2 <= 2;$var2++)
    {
        echo 'Nested Loop ' . "$var2" . " times <br/>";
    }
    echo "<br/> ";
}
?>

Output

PHP ***Nested For loop*** Example
------------Nested For loop ------------------
Outer Loop 1 times
Nested Loop 1 times
Nested Loop 2 times

Outer Loop 2 times
Nested Loop 1 times
Nested Loop 2 times

Outer Loop 3 times
Nested Loop 1 times
Nested Loop 2 times

Outer Loop 4 times
Nested Loop 1 times
Nested Loop 2 times

This concludes the PHP for Loop lesson. In the next lesson, you will learn about the foreach loop in PHP programming.