The do while loop is similar to the while except that the test is at the end of the loop. The do while always executes at least once.
Example 1: The code below will print 1 2 3 4 5 6 7 8 9 10
$i=1;
do {
echo $i.' ';
$i++;
} while($i<=10);
Compare this to the while and for loops that printed the numbers from 1 to 10.
Example 2: The code below will print
January February March April May
(January up to the current month)
$mth=1; //numeric representation of January
do {
$date=mktime(0,0,0,$mth,1,2009); //January, any year
echo date("F",$date).' ';
$mth++;
}while($mth<=date("n"));
The do loop is often used in a search, we know that we have to look in the first position and we will search until we find what we are looking for.
Experiment: Write each of the following using a for, a while, and a do...while. Think about which was was easier for each example.