Table of Contents



Introduction

do-while loops are very similar to while loops except that the truth expression is checked at the end of each iteration instead of at the beginning. The main difference from the regular while loops is that the first iteration of a do-while loop is guaranteed to run. This is because the truth expression is only checked at the end of the iteration.

Syntax of the do...while Loop

The syntax of the do...while loop is given as:

Syntax

The do...while loop.

1do {
2    statements;
3}   while (expression);

The do...while loop will always execute the statements once, and then it will check the expression, and repeat the loop while the specified expression evaluates to true. However, when the truth expression evaluates to false, the loop execution ends.

ADVERTISEMENT



Using the do...while Loop

Example

Using the do...while loop.

1<?php
2    $x = 1;
3    do {
4        echo "The number is: $x <br>";
5        $x++;
6    }   while ($x <= 5);
7?>
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

The above results can also be generated by the following shorter code where the increment in $x is included in the truth expression.

Example

Using the do...while loop (shorter version).

1<?php
2    $x = 1;
3    do {
4        echo "The number is: $x <br>";
5    }   while (++$x <= 5);
6?>
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

Note that the expression ++$x <= 5 tells PHP to first make the increment before evaluating the truth expression.

Example

Using the while loop to generate a 3 times table.

1<?php
2    $count = 1;
3    do {
4        echo "$count times 3 is " . $count * 3 . "<br>";
5    }   while (++$count <= 10);
6?>
1 times 3 is 3
2 times 3 is 6
3 times 3 is 9
4 times 3 is 12
5 times 3 is 15
6 times 3 is 18
7 times 3 is 21
8 times 3 is 24
9 times 3 is 27
10 times 3 is 30