|
|
Loops II - The while Loop
The while Loop
A while loop takes the form:
while (condition) {
//Do something.
}
The condition is checked before each iteration of the loop, and if condition evaluates to false, the loop does not run, and the flow of execution continues outside the loop.
The do...while Loop
The do...while loop has a very similar structure:
do {
//Do something.
} while (condition);
Here, the condition is checked after each iteration of the loop; thus, the code within the loop will be executed once before the condition is evaulated. See the following two examples:
<?php
echo("While loop:<br>");
$i=0;
while($i < 5) {
echo("\$i = $i<br>");
$i++;
}
//-----------------------
echo(" <br>Do...while loop:<br>");
$i=0;
do {
$i++;
echo("\$i = $i<br>");
}while($i < 5);
?>
Output:
While loop:
$i = 0; $i = 1; $i = 2; $i = 3; $i = 4; Do...while loop: $i = 1; $i = 2; $i = 3; $i = 4; $i = 5; Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|