PHP While Loop Statements


In this article, you will learn about PHP while loop and do while loop with examples. Loops, in general, execute a block of code until a specified condition is met.

PHP while loop

 PHP while loop


Loops are used to execute the same block until the condition is true. We can use the same code as many times as we want. But it won’t be practical and will be more time-consuming. So, loops in PHP are used to execute the same block code for a certain number of times. And While loops are used to execute the same block until the condition is true.

PHP while loop flowchart

php while loop flow chart

As you can see in the flowchart, the statement is executed until the imposed condition is true and once it is false, the flow breaks out of the while loop.

Basic statement of PHP while loop:

While (expr)
 Statement

General form of PHP while statement

initialize loop counter;

while (test loop counter using condition)

{

 execute the statement

  ....... 

  .......

 increment loop counter

}

Now, let’s check this basic example of while loops for better understanding:


  <?php  

  $x = 1;

  while($x <= 8) {

    echo "The number is: $x <br>";

    $x++;

  } 

  ?>  

Output:

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The number is: 6

The number is: 7

The number is: 8

Beginner mistake:

Check the expression until there are no any human errors.

 PHP do while loop statement

Difference between While and do while loops is the place where the condition is tested. Do while loop tests if condition after having executed the statements within the loop once. It means statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.

The general form of PHP do while statement:

do {

Code to be executed;

}

While(condition);

Now, let’s check this basic example of PHP do while loops for better understanding:


<?php

$a=1;

do {

echo "count number : $a <br />";

echo "I am learning PHP  <br />";

$a=$a+1;

}while ($a<=4)

?>

Here is the flowchart of the above program for better understanding.

do while loop flow chart

 

Summary

  • While loop is used to execute a block of code as long as the condition is true.
  • Do…while loop is used to execute the block of code at least once, then the rest of the execution is dependent on condition.