Tuesday, May 10, 2016

do while statement

do...while statement is a little like while statement turned on its head. The essential difference between the two is that the code block is executed before condition test and not after it.

do {
// code to be executed
//increment or decrement
} while (expression of condition) ; // only if condition is true, the code block is repeated

Remember that do...while statement always ends with a semicolon.

This type of statement will be useful when we want the code block to be executed at least once, even if in while statement evaluates to false. The code block below is executed a minimum of one time:

<?php
$i = 1;
do {
echo "The number is: $i<br />";
$i++;
} while (($i > 10) && ($i < 20));
?>

The do...while statement tests whether the variable $i contains a value that is greater than 10 and less than 20. In line 2, we initialized $1 to 1, so this expression returns false. Nonetheless, the code block is executed at least one time before the condition is evaluated, so the statement will print a single line to the browser.

The number is: 1

If we change the value of $i in line 2 to something like 10 and then run the script, the loop will display
The number is: 10
The number is: 11
The number is: 12
The number is: 13
The number is: 14
The number is: 15
The number is: 16
The number is: 17
The number is: 18
The number is: 19