Primary links
do while Loop
admin — Wed, 13/09/2006 - 8:15pm
do while loops
The “do...while” statement is similar to the “while” statement. The only difference between the two is that when using the “do...while” statement the block of statements is executed if and as long as a condition is true.
The do...while loop is similar in nature to the doloop discussed in the previous section. The key difference is that the do...while loop body is guaranteed to run at least once. This is possible because the condition statement is evaluated at the end of the loop statement after the loop body is performed.
The basic do...while loop syntax is shown below:
do {
code to be executed;
}
while (condition);
The code within a while loop will repeatedly execute as long as the condition at the end of the loop evaluates to true. The code block associated with the while statement is always enclosed within the { opening and } closing brace symbols.
The following example demonstrates a while loop that continues to execute as long as the variable $number is greater than or equal to 2:
$number = 5;
do {
echo $number . "<br/>";
$number -= 1;
{
while ($number >= 2);
In the above example, the variable $number1 is initialized to 5. The do...while loop executes as long as the condition, ($number1 >=2), or $number1 is greater than or equal to 2, printing the value of $number1 to the browser window. At the end of the loop block, the value of $number1 is decreased by 1.
Below is the output generated by the sample loop:
5
4
3
2
During the first run, the value of $number is equal to 5. Since the condition for a do loop is not checked until after the loop has run once, the value of $number, 5 is displayed. Next, the value of $number is decremented by 1, becoming 4. Since 4 is greater than 2, the loop runs again and during the second iteration the echo statement is used to display the value 4. A <br/> is concatenated to the display to create a carriage return each time the loop is processed. This process continues while the value of $number is 3 and 2. When $number is equal to 2, the echo statement displays the value 2 and the value of $number is then decremented to 1. Since 1 is not greater than or equal to 2, the condition is no longer true and the while loop ends.
User login
Follow Us
Who's online
Who's new
- Nisha
- linnaeus
- Yameen
- TalleyReedy
- admin

