PHP loops. How to repeat a block of code without writing it out again and again.
Understanding loops in PHP
Loops run the same block of code repeatedly while a condition holds. PHP has several loop types, each suited to slightly different situations.
The while loop
A while loop checks its condition first, then runs the code block if the condition is true:
<?php
$counter = 1;
while ($counter <= 5) {
echo "Loop iteration: $counter <br>";
$counter++;
}
?>
This runs five times, printing the counter value each time.
The do...while loop
A do...while loop runs its body once before checking the condition, so the code inside always executes at least once:
<?php
$counter = 1;
do {
echo "Loop iteration: $counter <br>";
$counter++;
} while ($counter <= 5);
?>
Even if $counter starts above 5, the loop body still runs once.
The for loop
Use a for loop when you know exactly how many iterations you need. Initialisation, condition, and increment all sit on one line:
<?php
for ($counter = 1; $counter <= 5; $counter++) {
echo "Loop iteration: $counter <br>";
}
?>
The foreach loop
foreach is the easiest way to loop through an array:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $color) {
echo "Color: $color <br>";
}
?>
Each colour is printed in turn.
Breaking out of loops
Use break to exit a loop early:
<?php
for ($counter = 1; $counter <= 10; $counter++) {
if ($counter == 6) {
break;
}
echo "Loop iteration: $counter <br>";
}
?>
The loop stops when $counter reaches 6.
Skipping iterations with continue
Use continue to skip the rest of the current iteration and move to the next:
<?php
for ($counter = 1; $counter <= 5; $counter++) {
if ($counter == 3) {
continue;
}
echo "Loop iteration: $counter <br>";
}
?>
The number 3 is skipped in the output.
Nested loops
You can put a loop inside another loop. Nested loops are useful for multidimensional arrays and building grid-like output:
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i - $j <br>";
}
}
?>
This prints every combination of $i and $j.
Practical example: creating a table
Nested loops are a common way to generate HTML tables:
<?php
echo "<table border='1'>";
for ($row = 1; $row <= 5; $row++) {
echo "<tr>";
for ($col = 1; $col <= 5; $col++) {
echo "<td>Row $row - Column $col</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This builds a 5×5 HTML table – a good test that your nested loops are working.
Loops save you from writing the same code repeatedly. The table example is worth typing out yourself. Next up: functions – reusable blocks of code you can call from anywhere in your script.

