PHP do while loop

In this chapter you will learn:

  1. What is a do while loop
  2. Syntax for do while loop
  3. Example - do while loop with integer counter

Description

The PHP do...while construct is similar to a while loop. The difference is that the do...while loop is executed at least once.

Syntax

The do while loop has the following syntax.


do{
  loop body
}while(condition is true);

Example

Consider the following piece of code:


<?php//jav  a2  s . c om
        $i = 1;
        do {
                print "Number $i\n";
        } while ($i < 10);
?>

In comparison, that same code could be written using a while loop:


<?php/*from  j a v  a 2s .  c om*/
        $i = 1;
        while ($i < 10) {
                print "Number $i\n";
        }
?>

The difference is that the while loop would output nothing, because it checks the value of $i before entering the loop. Therefore, do...while loops are always executed a minimum of once.

Next chapter...

What you will learn in the next chapter:

  1. What is for loop
  2. for loop Syntax
  3. Example - for loop with
  4. Example - Infinite Loops
  5. Example - Loops Within Loops
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require