PHP Tutorial – do…while Loops

The do…while statement will always execute the block of code once. After this first execute it will check the condition, and repeat the loop (keep executing) while the condition is true.

Syntax


do
{
     code to be executed;
}
while (condition);

do…while loop example

Ok, let’s look at an example:


<html>
<body>

<?php
     $x=1;
     do
     {
          $x++;
          echo "The number is " . $x . "<br />";
     }
     while ($x<=5);
?>

</body>
</html>

We start with setting X to 1. Then we enter the loop and increment X. Then X is printed onto the screen. The last action of the loop is to check if X is less or equal to 5. If this is true the loop runs another time.

So the output of our example will be:


The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

Also take a look at the other PHP language loop statements:

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

Leave a Reply: