While Loop in PHP

The while loop in PHP programming language is the simplest type of loop statement that repeats a block of code or a target statement(s) as long as the specified condition remains true.

In simple terms, a while loop will keep looping as long as the specified condition is met. It is an entry-controlled loop statement, meaning that the test condition is evaluated before the code block executes.

If the specified condition is true, the code block executes. If the specified condition does not satisfy, the code block does not execute. Thus, the while loop executes a block of statements repeatedly as long as the test condition is true. Each repetition of the loop’s body is called iteration.

The while loop in PHP is especially useful in scenarios when the number of iterations is unknown and depends on a dynamic condition that may change during runtime.

Syntax of While Loop in PHP


When you want to write the while loop statement in a PHP program, you should use the following basic syntax:

<?php
while (condition) {
    // PHP code goes here.
}
?>

In the above syntax of while loop:

  • while is a keyword in PHP used to define the loop.
  • The condition is boolean expression, usually a comparison or logical expression that returns either true or false. The condition is placed within parentheses immediately following the while keyword.
  • The loop body is the part of the while loop that contains the code block or statements to be executed repeatedly as long as the condition evaluates to true. It can contain one or more statements.

If the loop body consists of two or more statements, curly braces {} are mandatory to group these statements together. However, even if the loop body contains only a single statement, it is a good programming practice to use curly braces for clearness and to avoid any kind of errors when adding more statements later.

How Does a While Loop Work?


Let’s understand the working of a while loop in PHP programming:

1. Before while loop begins, the initialization part is executed. It is basically a loop counter variable (commonly called the loop counter) that sets the starting value of the variable controlling the loop.

2. Next, the test condition or expression inside the parentheses of the while statement is executed. If the test condition evaluates to true, the loop’s body (i.e. a block of code) executes. After the execution of the loop body, the test condition is re-evaluated.


3. If the condition is still true, the loop body executes again. This process of repeatedly executing the loop body continues until the condition becomes false.

4. After the executing the statements inside the while block, the control goes to increment or decrement part. It will increment or decrement the value of loop control variable by one.

5. Next, again, the control goes to evaluate the condition. If it evaluates to false, the loop ends and the control of execution transfers out of the loop.

6. On exit, the program continues with the next statement immediately after closing curly braces of while loop.

The flowchart diagram of while loop statement in PHP is shown in the below figure.

Flowchart diagram of while loop in PHP

Let’s understand the working of while loop with a very simple example.


Example 1:

<?php
// Initialization of control variable. This variable has defined outside the loop and will update inside the loop.
$i = 1;

// Declare while loop statement.
while($i <= 5) {
// Body of the loop.
   echo $i . "\n"; // This statement will execute until the condition is true.
   $i++; // It counts the number of execution and increments the value of $i by one.
}
?>
Output:
       1
       2
       3
       4
       5

In this example, we have declared a loop control variable named $i whose initial value is set to 1. The variable acts as a counter and controls the whole loop. Next, we have declared a conditional expression ($i <= 5) inside the parentheses of while statement which evaluates to true.

If the expression evaluates to true, the statements inside the loop body will execute. Else, the body of loop will be skipped. After the executing statement inside the while block, the execution of control goes to the increment part ($i++) which will increment the value of control variable by one.

After incrementing it, the control again goes to evaluate the conditional expression inside the while statement. If it is true, the while block again executes. This process continues to repeat until the value of variable $i becomes less than or equal to the value 5.

Examples of PHP While Loop Statement


Example 1: Let’s write a simple PHP program to display a “Hello World!” four times using a while loop.

<?php
$i = 1;
while($i < 5) {
   echo "Hello World!" . "\n";
   $i++;
}
?>
Output:
      Hello World!
      Hello World!
      Hello World!
      Hello World!

Example 2: Let’s write a PHP program to display numbers from 5 to 1 by using the while loop statement.

<?php
$i = 5;
while($i >= 1) {
   echo $i . "\n";
   $i--; // Decrement.
}
?>
Output: 
       5
       4
       3
       2
       1

Example 3: Let us write a PHP program to calculate the sum of the first 10 natural numbers using the while loop.

<?php
$sum = 0;
$i = 1;
while ($i <= 10) {
 // Adds the current value of $i to $sum and updates $sum.
    $sum = $sum + $i;
    $i++; // Increments $i by 1
}
echo "Sum = " . $sum;
?>
Output:
      Sum = 55

In this example, the variable $i is initially set to 1 and the $sum to 0. The while loop will continue to execute the block of code as long as the value of $i is less than or equal to 10.


If the condition ($i <= 10) evaluates to true, the loop body executes. In each iteration, the program control adds the value of $i to $sum. Then, the variable $i is incremented by one after each iteration. This process continues up to 10. Look at the step by step execution.

1. Initially: $sum = 0, $i = 1.

2. Loop starts:

  • Iteration 1: $sum = 0 + 1 = 1, $i = 2.
  • Iteration 2: $sum = 1 + 2 = 3, $i = 3.
  • Iteration 3: $sum = 3 + 3 = 6, $i = 4.
  • Iteration 10: $sum = 45 + 10 = 55, $i = 11.

After 10th iteration, the loop ends because $i becomes 11, which does not satisfy the condition ($i <= 10) and the control of execution exits the loop. In this way, the final value of $sum (1 + 2 + 3 +… + 10 = 55) is displayed.


Example 4: Let’s take an example in which we will display numbers between 5 and 10 using while loop statement.

<?php
$x = 6;
echo "Numbers between 5 and 10 are: ";
while ($x > 5 AND $x < 10) {
   echo $x . " ";
   $x++;
}
?>
Output:
      Numbers between 5 and 10 are: 6 7 8 9

Advanced Examples of While Loop


Example 5: Let’s write a program to print even numbers from 1 to 20.

<?php
// Initialize the counter
$i = 1;
echo "Even numbers from 1 to 20: ";
while ($i <= 20) {
  // Check if the number is even.
     if ($i % 2 == 0) {
        echo $i . " "; // Display the even number
     }
     $i++; // Increment the counter
}
?>
Output:
      Even numbers from 1 to 20: 2 4 6 8 10 12 14 16 18 20 

Example 6: Let’s write a PHP program to display the factorial of number 10 using while loop.

<?php
$num = 1;
$fact = 1;
while($num <= 10){
   $fact = $fact * $num;
   $num++;
}
echo "The factorial of 10 is " . $fact;
?>
Output:
      The factorial of 10 is 3628800

Example 7: Let’s write a PHP program to display the mathematical table 5.

<?php
$num = 5;
$i = 1;
$tab = 0;
echo "Mathematical table of 5: " . "\n";
while($i <= 10) {
    $tab = $num * $i;
    echo $num . " * " . $i . " = " . $tab . "\n";
    $i++;
}
?>
Output:
     Mathematical table of 5: 
     5 * 1 = 5
     5 * 2 = 10
     5 * 3 = 15
     5 * 4 = 20
     5 * 5 = 25
     5 * 6 = 30
     5 * 7 = 35
     5 * 8 = 40
     5 * 9 = 45
     5 * 10 = 50

Nested While Loops in PHP


Like nested for loops, you can also nest one while loop inside another to handle multidimensional data structures or perform complex operations. When you put one while loop inside another, it is called nested while loops. Let’s take an example on it.

Example 8:

<?php
$row = 1;
// Outer loop.
while ($row <= 3) {
   $col = 1;
// Inner loop.
   while ($col <= 3) {
      echo "Row $row - Column $col". "\n";
      $col++;
   }
   $row++;
}
?>
Output:
      Row 1 - Column 1
      Row 1 - Column 2
      Row 1 - Column 3
      Row 2 - Column 1
      Row 2 - Column 2
      Row 2 - Column 3
      Row 3 - Column 1
      Row 3 - Column 2
      Row 3 - Column 3

Example 9: Let’s write a PHP code to display a right triangle of * using nested while loop.

<?php
$i = 1;
echo "Displaying a right triangle of *: " . "\n";
while ($i <= 5) {
   $j = 1;
   while ($j <= $i) {
       echo "*" . " ";
       $j++;
   }
  echo "\n";
  $i++;
}
?>
Output:
     Displaying a right triangle of *: 
     * 
     * * 
     * * * 
     * * * * 
     * * * * * 

Infinite While Loop


If the conditional expression in a while loop always evaluates to true, the loop will become an infinite loop, and the program will never exit the loop. Let’s see an example code.

Example 10:

<?php
$i = 1;
while ($i > 0) { // This condition is always true because $i is never updated.
    echo $i . " ";
}
?>

In this example, the loop will never end because $i is not updated, and the condition ($i > 0) will always be true. You can stop it using the break statement.

Example 11:

<?php
$i = 1;
while ($i > 0) { // Infinite loop condition
   echo $i . " ";
   if ($i == 5) // Check if $i is equal to 5
      break; // Exit the loop
   $i++; // Increment $i to avoid an infinite loop
}
?>
Output:
     1 2 3 4 5

Here, you learned while loop statement in PHP programming with basic to advanced examples. I hope that you have understood to use while loop and practiced all examples discussed in this tutorial.