PHP - While and do-while

  »   PHP Introduction  »   PHP Tutorial - While and do-while

The PHP while statement is used to run a code in loop over and over again. This is very useful and helps you minimize the code for rapid edition and maintenance. There are several loop statements that can be used depending on your needs

  • while - repeats a block of code as long as the condition is met
  • do / while - executes a block of code once, and then repeats it as long as the condition is met
  • for - executes a block of code a given number of times
  • foreach - executes a block of code for each element of an array

PHP while loop

Here is a simplified example of the while statement

phpwhile (expression == true) {
    // run this block of code;
}

This is a practical example of the PHP while loop. We need to execute the code 10 times in a loop. Here is how we do it.

php<?php 
$counter = 1;
$max = 5;

while($counter <= $max) {
    echo "This is number $counter loop, we have ".($max - $counter)." left.<br />";
    $counter++;
} 
?>

The above PHP code will print something similar to this

phpThis is the number 1 loop, we have 4 left.
This is the number 2 loop, we have 3 left.
This is the number 3 loop, we have 2 left.
This is the number 4 loop, we have 1 left.
This is the number 5 loop, we have 0 left.

How to use PHP do-while statement

Since we already learned the while syntax, the do-while is practically the same with one exception. The first loop will always execute no matter if the condition is true or false. This is great to use, for example, when you need to repeat the code operation depending on the result of the first iteration. Remember in a do-while statement the condition is evaluated after the first loop

phpdo {
    # execute this code first and then check the condition
} while (expression == true);

So let's take our previous example and transform it to a do-while syntax instead of a simple while loop.

php<?php 
$counter = 1;
$max = 0;

do {
    echo "This is number $counter loop, we have ".($max - $counter)." left.<br />";
    $counter++;
} while($counter <= $max);
?>

You wold expect that the echo will not execute since the $max = 0. But this is not the case since we are checking the $max value after executing the do loop

While and do-while alternative syntax

The PHP while statements has an alternative syntax for you to use. Take a look at the next example. We are using the colon punctuation mark and the endwhile to end the syntax

php<?php 
$i = 1;
while ($i <= 5):
    print $i;
    $i++;
endwhile;
?>

On the other hand, there is NO alternative syntax for the do-while loop statement. Easy as that.