PHP while Loop

In this lesson, you will learn about the while Loop and Nested while Loops in PHP, along with examples to understand the topic better.


PHP while Loop

A while loop is a loop that continuously executes until a condition is met. You can also use a while loop to read records returned from a database query or iterate through an array or generic type. If the condition is assessed to be valid, the code block is executed as long as the condition is satisfied. The while loop’s execution stops if the condition is false.


Basic Syntax

< ? php
while (condition) {
  block of code to be processed here;
} ?>

while Loop Flowchart

 

Example

The code below prints the table of 2 and executes the ‘while’ loop until var becomes equal to 10.

<?php
echo "PHP ***While loop*** Example";
echo "<br>";
echo " ------------while loop ------------------ ";
echo "<br>";
echo "The table of 2 ";
echo "<br>";
$var = 1;
while ($var <= 10)
{
    $evennumber = 2 * $var;

    echo "2 * $var is $evennumber <br/>";
    $var++;
}
?>

Output

PHP ***While loop*** Example
------------while 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 while Loop Statement

Nested while loops in PHP allow us to use a while loop inside another while loop.

Nested while Loops Flowchart

 

Example

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

        echo 'Nested Loop ' . "$var2" . " times <br/>";
        $var2++;
    }
    $var++;
    echo "<br/> ";
} ?>

Output

PHP ***Nested While loop*** Example
------------Nested While 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

A nested loop is fully executed for one outer loop in the case of an inner or nested loop. If the outer loop is to be executed 4 times and the inner loop 2 times, the inner loop will be executed eight times (2 times for the first outer loop, 2 times for the second outer loop, 2 times for the third outer loop, and 2 times for the fourth outer loop).

This concludes the PHP while Loop lesson. The next lesson will teach you about PHP’s do…while loop.