|
| HOW TO USE do while LOOPS IN PHP
A do while loop differs from a while loop in that it always executes a block of code at least once even if the condition below evaluates to false. This is because it executes a block of code first and then checks the condition which is below the block of code.
The general format is:
do {
execute this code;
}
while(certain condition);
Example:
$price = 5;
do {
echo $price."<br>";
$price++;
}
while ($price < 10 );
The above will output:
5
6
7
8
9
We set our variable $price with a start value of 5. Since do while loops always execute the block of code at least once, $price has value of 5 and is echoed as 5. Then $price is incremented by 1 and $price now has value of 6.
Since $price of value of 6 is still less than 10 (in our condition), 6 is echoed, then incremented by 1 to 7 and so forth until the value of 9 has echoed. Then $price has value of 9 + 1 and is not less than 10 anymore so our code stops executing.
|
|