agyanadda@gmail.com

PHP Loops

Operators and Control Flow 1 min read Updated Dec 1, 2026 Topic 14 of 36

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 loop
  • continue — 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."

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which loop is best for going through every item of an array?

Exercise 2 True / False

A do...while loop always runs at least once.

Exercise 3 Fill in the Blank

___ exits a loop immediately.

Frequently Asked Questions

Probably an infinite loop — the condition never becomes false (e.g. you forgot $i++). PHP stops it after max_execution_time (usually 30 seconds).