The while loop in PHP is a type of loop that can be used to repeat a block of PHP code until the loop exit the execution when it return false by the condition.

The case of use for this loop type that when the iteration has unknown number and you set a condition inside the loop to exit once it reaches the false.

Anyway, the expression of PHP while can be written like the following structure.

<?php 
  While ( expression ) {
   // .. the statement code here.
  }
?>

Let’s see more examples for PHP while loop and how it does work.

How the While Loop Works in PHP?

Check the following figure you will see the full task for the PHP while loop.

how to use while loop in PHP

As you understood, the while is doing a loop until it reaches the false to exit the loop, so if it has true it will execute the statement part.

For example

<?php
  $i = 0;
  While( $i < 10 ) {
    echo " $i <br />";	
   
    $i++;
  }
?>

The output would be like this  0 1 2 3 4 5 6 7 8 9

So if the condition is returning true when the $i is smaller than 10 so it will do another loop.

Each time it will do the same task, once it reaches the 10 result then it will exit the loop.

In the next section, I will focus on the one statement syntax for PHP while loop. Let’s move forward.

PHP While Infinite Loop

To execute only one line inside the while loop you have to use the following pattern in your PHP code.

while( true ) 
   … statement

This pattern only executes the first line after the condition brace. In this syntax there are no curly braces.

For example.

<?php
  while( true )
    echo "CodedTag.com ";
?>

Anyway, in the next section I will move to the embedded while loop pattern and how it does work.

Embedded PHP While Loop with HTML Markups

The embedded while loop can be worked with any code else such as JavaScript or HTML markup language.

The main pattern for this syntax can be like the following one.

<?php  while( true ): ?>
    // .. JavaScript, PHP, HTML, OR whatever here ..
<?php endwhile; ?>

So, it executes the statement pattern according to the condition. For example.

<?php 
 
  $i = 0;
  while( $i < 5 ): ?>
  <h1>Welcome to CodedTag Tutorials.. </h1>
<?php endwhile; ?>

That’s all, in the next section I will move to the nested while loop.

Usage of Nested While Loop

The nested while loop means that you can use while loop inside another while loop. Let’s see an example;

This example will print the multiplication table.

<?php 

  $basic = 1;
  while($basic <= 12 ) {
     $factor = 1;
     while( $factor <= 12 ) {
       echo $basic . " x " . $factor . " = " . ($basic * $factor); // z x y = xyz
       echo "<br />";
       $factor++;
     }
  
  
     $basic++;

  }

?>

Let’s summarize the while loop in a few points.

Wrapping Up

In this article, you learned about while loop and you saw many examples for it such as: Nested while loop, one statement while loop, infinite while loop with no curly braces example.