Looping Statements

Looping statements allow a block of statements to be repeated 0 or more times depending upon a certain condition.

Contents

While loops

while (conditional expression) 
{
  code to execute;  // Contains a statement that eventually makes condition FALSE    
}

// Example
$n = 1;
while ($n <= 10) {
   echo "n equals $n<br>";
   $n++;             // Eventually $n > 10 and the loop stops.
}
echo "Done";

Do-while loops

In the do-while loop the condition occurs after the statement block so the block is executed at least once.

do {
   code to execute; 
} while (conditional expression);

// Example
$n = 1;      // Loop initialization
do {
   echo "n equals $n<br>";
   $n++;         // Loop Modification: Eventually $n > 10 and the loop stops.
} while ($n <= 10); // Loop Condition
echo "Done";

For loops

The for loop provides the same functionality as the while and do-while loop but puts everything together into a single statement:

for (initialization expression;  conditional expression; modification expression) {
    code that is executed;
}

// Example
for ($n=1; $n <= 10; $n++) {
    echo "n equals $n<BR>";
}

Homework Exercise

Write a PHP script that contains a for loop that prints the values from 0 to n that are divisible by m. For example if n is 20 and m is 3, then your loop should print: 0, 3, 6, 9, 12, 15, 18. If m were 5, it should print 0, 5, 10, 15, 20. Click here for a solution.