Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

While loop

while loops through a block of code as long as the condition is true.

while (condition is true) {
  code to be executed;
}

Do…while loop

Do...while loops through a block of code once, and repeats the loop as long as the condition is true.

do {
  code to be executed;
} while (condition is true);

For loop

for loop loops through a block of code a specified number of times.

for (init counter; test counter; increment counter) {
  code to be executed for each iteration;
}

For example

<?php
for ($i = 0; $i <= 5; $i++) {
  echo "The number is: $i <br>";
}
?>

Breaking Out of a Loop

The break statement ends the current loop and jumps to the statement immediately following the loop.

for ($count = 1; $count <= 10; $count++ ) {
  if ( $count == 5 ) break;
  echo "Count: $count\n";
}
echo "Done\n";
/* Output:
Count: 1
Count: 2
Count: 3
Count: 4
Done
*/

continue keyword

The continue statement ends the current iteration. jumps to the top of the loop, and starts the next iteration.

for($count=1; $count<=10; $count++ ) {
  if ( ($count % 2) == 0 ) continue;
  echo "Count: $count\n";
}
echo "Done\n";
/* Output:
Count: 1
Count: 3
Count: 5
Count: 7
Count: 9
Done
*/