Basic
Advanced
Examples
PHP 8 - Loop
Last modified: April 02, 2022In PHP, we have the following loop types:
- while run as long as the specified condition is true
- do...while run once and run as long as the specified condition is true
- for run for specified number of times
- foreach run as each element in an array
1. while
<?php
$x = 1;
while ($x <= 3) {
echo "$x <br>";
$x++;
}
?>
Outcome
2. do...while
<?php
$x = 1;
do {
echo "$x <br>";
$x++;
} while ($x <= 3);
?>
Outcome
3. for
<?php
for ($x = 0; $x <= 3; $x++) {
echo "$x <br>";
}
?>
Outcome
4. foreach
<?php
$countries = array("HK", "USA", "UK");
foreach ($countries as $value) {
echo "$value <br>";
}
?>
Outcome
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>";
}
?>