PHP Do While Loop Tutorial

The PHP do while loop behaves only slightly differently from the regular PHP while loop. The only difference between the 2 loops is that the DO while loop will execute its block of code at least once. That is, its block of code will be run once before the interpreter checks the condition.

So the do while loop is useful in a situation where we want to repeat something as long as a condition holds but we also want the loop to run at least once.

In the tutorial below, we will look at the syntax of the PHP do while loop and how to properly use it in our code.

PHP Do While Loop Syntax

The Do While Loop in PHP is defined as follows:

do
{
    // execute some commands
}
while (condition);

That is all that is needed to get a Do While loop working in PHP. Remember that condition is a statement that evaluates to true or false.

PHP Do While Loop Example

The Do While Loop is quite easy to construct and use as we can see in the example below. You can copy the code directly to a PHP script to test it.

<?php
 
$count = 0;
 
do
{
    echo 'Tutorial Arena rocks!';
}
while ($count != 0);
 
?>

The resulting output will be:

Tutorial Arena rocks!

We purposefully set the counter variable $count to 0 to demonstrate that the code inside the loop will execute at least once. Remember though, that you need to manipulate the counter variable from inside the loop to ensure that the condition will become false at some point. If you forget to do this, your script will hang inside the loop.

PHP Do While Loop Example 2

Look at this code:

<?php
 
$count = 9;
 
do
{
    echo "$count - Tutorial Arena rocks!";
    echo '<br />';
    $count--;
}
while ($count > 0);
 
?>

Result:

9 - Tutorial Arena rocks!
8 - Tutorial Arena rocks!
7 - Tutorial Arena rocks!
6 - Tutorial Arena rocks!
5 - Tutorial Arena rocks!
4 - Tutorial Arena rocks!
3 - Tutorial Arena rocks!
2 - Tutorial Arena rocks!
1 - Tutorial Arena rocks!

We first initialised our counter to 9 and then output our data to the screen. After we output the data each time, we decrement our counter by 1. PHP will exit the Do While Loop after the counter variable is not greater than 0. That is why the loop in the example above stopped when $count was 1; as 1 was the last value which was greater than 0;

That is all there is to the Do While Loop in PHP. We hope the PHP Do While Loop tutorial was helpful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...