Control Flow Lesson 8 of 17
PHP Loops — for, while, do-while and foreach
Repeat code in PHP with for, while, do-while and foreach loops, build HTML tables and lists from loops, and use break and continue.
Loops are how PHP builds repeated parts of a page: rows of a table, items of a menu, a list of products from a database.
for
<?php
for ($i = 1; $i <= 5; $i++) {
echo "7 x $i = " . 7 * $i . "\n";
}
Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
while and do-while
<?php
$savings = 0;
$weeks = 0;
while ($savings < 1000) {
$savings += 150;
$weeks++;
}
echo "$weeks weeks, ₱$savings\n";
$n = 0;
do {
echo "Runs at least once\n";
} while ($n > 0);
Output
7 weeks, ₱1050 Runs at least once
foreach: the PHP favorite
foreach goes through every item of an array. It's the loop you'll use most in PHP:
<?php
$subjects = ["Math", "Science", "English"];
foreach ($subjects as $subject) {
echo "- $subject\n";
}
$prices = ["Pandesal" => 25, "Kape" => 8, "Itlog" => 9];
foreach ($prices as $item => $price) {
echo "$item: ₱$price\n";
}
Output
- Math - Science - English Pandesal: ₱25 Kape: ₱8 Itlog: ₱9
With $key => $value, you get both the key and the value of each element.
Building an HTML table
<?php
$students = [
["name" => "Ana", "grade" => 91],
["name" => "Ben", "grade" => 74],
["name" => "Carla", "grade" => 88],
];
?>
<table>
<tr><th>Name</th><th>Grade</th><th>Remark</th></tr>
<?php foreach ($students as $s): ?>
<tr>
<td><?= htmlspecialchars($s["name"]) ?></td>
<td><?= $s["grade"] ?></td>
<td><?= $s["grade"] >= 75 ? "Passed" : "Failed" ?></td>
</tr>
<?php endforeach; ?>
</table>
HTML output
<table>
<tr><th>Name</th><th>Grade</th><th>Remark</th></tr>
<tr>
<td>Ana</td>
<td>91</td>
<td>Passed</td>
</tr>
<tr>
<td>Ben</td>
<td>74</td>
<td>Failed</td>
</tr>
<tr>
<td>Carla</td>
<td>88</td>
<td>Passed</td>
</tr>
</table>This pattern (an array of rows and a foreach that outputs <tr> elements) is exactly how pages show data from a database.
break and continue
<?php
$stock = ["Pandesal" => 40, "Chips" => 0, "Kape" => 200, "Itlog" => 90];
foreach ($stock as $item => $qty) {
if ($qty === 0) continue; // skip sold-out items
echo "$item ($qty)\n";
if ($item === "Kape") break; // stop after Kape
}
Output
Pandesal (40) Kape (200)
Nested loops
<?php
for ($row = 1; $row <= 4; $row++) {
echo str_repeat(" ", 4 - $row) . str_repeat("*", 2 * $row - 1) . "\n";
}
Output
* *** ***** *******
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04