PHP 8 - Loop

Last modified: April 02, 2022

In PHP, we have the following loop types:

  1. while run as long as the specified condition is true
  2. do...while run once and run as long as the specified condition is true
  3. for run for specified number of times
  4. foreach run as each element in an array

1. while

<?php $x = 1; while ($x <= 3) { echo "$x <br>"; $x++; } ?>
Outcome

loop

2. do...while

<?php $x = 1; do { echo "$x <br>"; $x++; } while ($x <= 3); ?>
Outcome

loop

3. for

<?php for ($x = 0; $x <= 3; $x++) { echo "$x <br>"; } ?>
Outcome

loop

4. foreach

<?php $countries = array("HK", "USA", "UK"); foreach ($countries as $value) { echo "$value <br>"; } ?>
Outcome

loop

5. Break

The break statement can also be used to jump out of a loop.

<?php for ($x = 0; $x < 3; $x++) { if ($x == 2) { break; } echo "$x <br>"; } ?>

5. Continue

The continue statement breaks one iteration (in the loop)

<?php for ($x = 0; $x < 5; $x++) { if ($x == 2) { continue; } echo "$x <br>"; } ?>