for — known number of rounds
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
while — repeat while true
while ($balance < 10000) { ... }
do...while — runs at least once
do { ... } while ($condition);
foreach — loop through arrays (most used)
foreach ($courses as $course) { ... }
foreach ($marks as $subject => $mark) { ... }
break and continue
break— exit the loopcontinue— skip to the next round
Loops and HTML
Loops are how PHP builds tables, menus and product lists from database rows. The alternative syntax keeps templates clean:
<?php foreach ($rows as $row): ?>
<li><?= htmlspecialchars($row) ?></li>
<?php endforeach; ?>
Example
Example — Table, foreach and continue
PHP
<?php
$n = 9;
echo "<h4>Table of $n</h4>";
for ($i = 1; $i <= 10; $i++) {
echo "$n × $i = " . ($n * $i) . '<br>';
}
$marks = ['Hindi' => 78, 'English' => 25, 'Maths' => 92, 'Science' => 30];
echo '<h4>Passed subjects</h4><ul>';
foreach ($marks as $subject => $mark) {
if ($mark < 33) {
continue;
}
echo "<li>$subject: $mark</li>";
}
echo '</ul>';
$amount = 1000;
$years = 0;
while ($amount < 2000) {
$amount *= 1.08;
$years++;
}
echo "Money doubles in $years years at 8% interest.";
Output: the 9 times table, a list with Hindi: 78 and Maths: 92, and "Money doubles in 10 years at 8% interest."