Phase 1 · PHP FoundationsModule 6~40 min read

Loops & Iteration

Repeat work with while, for, and foreach, traverse real data, and choose between loops and array functions.

What you'll learn

Loops apply an operation repeatedly. You'll learn each PHP loop, iterate real nested data, implement common algorithms, and avoid a reference bug that catches experienced developers.

  • Choose between while, do-while, for, and foreach
  • Iterate array keys and values
  • Skip or stop work deliberately
  • Accumulate totals and counts
  • Recognize when an array function is clearer

while and do-while

A while loop checks before each iteration. A do...while checks after, so its body always runs at least once.

countdown.php
<?php

$seconds = 3;

while ($seconds > 0) {
    echo $seconds . PHP_EOL;
    $seconds--;
}

echo 'Launch!';

Every while loop needs progress

If the condition can stay true forever, the loop never ends. Identify which statement moves the state toward termination before you run it.

for loops

A for loop keeps initialization, condition, and update together. It is useful when the iteration count or index is central to the task.

multiples.php
<?php

for ($i = 1; $i <= 5; $i++) {
    echo ($i * 3) . PHP_EOL;
}

foreach is the default for arrays

foreach communicates that you care about each element rather than index arithmetic. Ask for the key only when it adds value.

course-list.php
<?php

$courses = [
    ['title' => 'PHP Foundations', 'minutes' => 40],
    ['title' => 'Web Fundamentals', 'minutes' => 46],
    ['title' => 'Modern PHP', 'minutes' => 50],
];

foreach ($courses as $index => $course) {
    $number = $index + 1;
    echo "{$number}. {$course['title']} ({$course['minutes']} min)" . PHP_EOL;
}
NeedBest starting point
Repeat until a condition changeswhile
Run at least once, then checkdo...while
Use an explicit numeric counterfor
Visit every item in an arrayforeach

break and continue

search.php
<?php

$ids = [0, 18, 27, 42, 55];

foreach ($ids as $id) {
    if ($id <= 0) {
        continue; // skip invalid values
    }

    if ($id === 42) {
        echo 'Found record 42';
        break; // stop searching
    }
}

continue skips to the next iteration. break exits the loop. Both are useful when they make a rule explicit; too many exit points can make flow harder to trace.

Accumulate useful results

Many loop algorithms maintain one or more accumulators: a running total, count, minimum, maximum, or grouped result.

orders.php
<?php

$orders = [42.50, 18.00, 120.75, 9.99];
$total = 0.0;
$largeOrders = 0;

foreach ($orders as $amount) {
    $total += $amount;

    if ($amount >= 100) {
        $largeOrders++;
    }
}

echo 'Total: $' . number_format($total, 2) . PHP_EOL;
echo "Large orders: {$largeOrders}";

Tip

After a loop works, ask whether array_sum(), array_filter(), or another focused function expresses the intent more directly. Keep the loop when multiple related results are calculated in one pass.

The foreach reference trap

references.php
<?php

$scores = [10, 20, 30];

foreach ($scores as &$score) {
    $score += 5;
}
unset($score); // break the lingering reference

print_r($scores);

Watch out

A referenced foreach variable stays bound to the last element after the loop. Always unset() it immediately—or prefer building a transformed array without references.

Recap & quick check

Key takeaways

  • while checks before; do-while runs at least once; for highlights counters; foreach visits array items.
  • Use key => value only when the key matters.
  • continue skips an iteration and break ends the loop.
  • Accumulators calculate totals, counts, minima, maxima, and grouped results.
  • Unset a foreach reference immediately after the loop.

Quick check

1. Which loop is usually clearest for visiting every array item?

2. What does continue do?

3. Why unset a referenced foreach variable?