Thuta Learning
PHP
IntermediateProgrammingBeginner

Loops (While, For, Foreach)

PHPLesson 1325 min

What you'll walk away with

  • Pick the loop (for, while, do-while or foreach) that fits the problem
  • Name the start, stop and step of any loop and avoid infinite loops and off-by-one mistakes
  • Predict what foreach by value and by reference do to an array, and prevent the leftover-reference bug with unset()
  • Use break N, continue N and [$a, $b] / list() unpacking inside foreach

Explain it simply

Explain it simply

A loop is a way of saying "do this again" without writing it again. Instead of copying the same echo line ten times, you write it once and tell PHP how long to keep repeating. A page that lists forty products, a report with a row per customer and a script that processes every line of a CSV file are all loops over some collection of data.

PHP has four loop statements, and the choice depends on what you are repeating over. for counts, while waits for a condition to change, do-while always runs at least once, and foreach walks through an array one element at a time. In everyday PHP you will write foreach far more often than the others, because so much of web programming is arrays: rows from a database, fields from a form, lines of a file.

Problem → Why → Solution

The problem: a loop that never stops and a loop that runs one step too far

Loops fail in two quiet ways. The first is a loop that never ends: the condition stays true because nothing inside the loop moves it towards false. The second is a loop that runs one step too many or too few. The code below has both. The for loop uses <= count(), so it reads one element past the end of the array, and the while loop never changes $n.

Running the first loop in the CLI prints the three names and then Warning: Undefined array key 3. The second loop never stops: a CLI script has no time limit (max_execution_time is 0 there), so it would print 5 over and over until you press Ctrl+C. In a web request PHP's default 30-second limit eventually ends it with a fatal error, but only after your server has been busy for half a minute.

broken-loops.php
<?php
$items = ["pen", "ruler", "eraser"];

// 1. Off by one: valid indexes are 0, 1, 2, but <= lets $i reach 3
for ($i = 0; $i <= count($items); $i++) {
    echo $items[$i] . "\n";
}

// 2. Nothing changes $n, so the condition is true forever
$n = 5;
while ($n > 0) {
    echo $n . "\n";
}

Why does PHP let this through?

PHP does not know what you meant. $i <= count($items) is a perfectly legal condition, and a loop with no update is legal too. Neither is a syntax error, so the first sign of trouble arrives at runtime, as a warning or as a frozen page. The cure is to decide, before you write the loop, what changes on every pass and which exact value ends it. For arrays, prefer foreach, which leaves no index to get wrong.

Core concept: every loop needs a start, a stop and a step

Every loop answers three questions: where does it start, when does it stop, and what changes between passes? A for loop puts all three in its header, for ($i = 0; $i < 10; $i++), which is why it suits counting. A while loop keeps only the condition in the header, so you must make sure the body changes something the condition looks at. do-while works the same way, except the condition is tested after the body, so the body always runs once. If you cannot say what pushes the loop towards its end, you have found the bug before running it.

LoopUse it when
foryou know the count or need the counter itself
whileyou repeat until something changes, such as reading a file to its end
do-whilethe body must run once before the first check, as in a retry
foreachyou have an array or other iterable and need every element

foreach deserves the most attention because it is the loop you will write most. foreach ($prices as $price) hands you each value, and foreach ($prices as $name => $price) hands you the key as well. By default the loop variable is a copy of the element, so assigning to it changes nothing in the array. PHP also loops over a snapshot of the array, so appending to it inside the loop does not extend the loop: an array of three elements that gets one element appended inside the loop is still visited three times, but ends up with four elements.

Two PHP-specific facts catch beginners. First, PHP has no block scope: variables from a loop header or body, such as $i or $price, are ordinary variables that still exist after the loop ends, holding the last value they had. Second, that survival turns dangerous with references, the subject of the first deeper section: a by-reference foreach leaves its variable tied to the last element until you unset() it. Add the control statements, where break leaves the loop, continue jumps to the next pass, and both accept a number such as break 2 to leave several nested loops at once, and you have everything the rest of the course needs.

Mental model: start, test, run, step
  1. Set the start value or pick the array
  2. Test the condition before each pass
  3. Run the body once for this pass
  4. Step forward, then test again

In foreach, PHP performs the step for you. In while you write the step yourself, and forgetting it is what makes a loop infinite.

General pattern

php
for (init; condition; step) { ... }

while (condition) { ... }

do { ... } while (condition);

foreach ($collection as $key => $value) { ... }

break;       // leave this loop (break 2 leaves two levels)
continue;    // jump to the next pass (continue 2 for the outer loop)

The for header has three parts separated by semicolons, while and do-while have a single condition, and in foreach the $key => part is optional. Giving break or continue a number makes it act on the outer loop levels as well.

Example: a counter, a countdown and a price list

This script uses three of the loops on small, realistic data. In the CLI each \n becomes a new row of output. In a browser you would add <br> or wrap each row in an HTML element, because browsers ignore plain newlines.

loops.php
<?php
// for: a counter you control
for ($day = 1; $day <= 3; $day++) {
    echo "Day $day\n";
}

// while: repeat until a condition changes
$stock = 12;
$weeks = 0;
while ($stock > 0) {
    $stock -= 4;
    $weeks++;
}
echo "Stock sold out after $weeks weeks\n";

// foreach: read every item together with its key
$prices = ["Laptop" => 1200, "Mouse" => 25, "Keyboard" => 70];
foreach ($prices as $name => $price) {
    echo str_pad($name, 10) . number_format($price) . " USD\n";
}

Code breakdown

  1. for headerfor ($day = 1; $day <= 3; $day++) {

    Start ($day = 1), stop condition ($day <= 3) and step ($day++) all sit on one line. When $day reaches 4 the condition is false and the loop ends.

  2. while conditionwhile ($stock > 0) {

    The loop repeats while stock remains. The header holds only the condition, so what ends the loop is a change made inside the body.

  3. the step$stock -= 4;

    This is the while loop's step. Selling 4 per week takes the stock from 12 to 0 in three passes. Remove this line and $stock stays at 12, so the loop never ends.

  4. foreach with keyforeach ($prices as $name => $price) {

    For each item of the associative array, the key goes into $name and the value into $price. There is no counter, so there is no index to get wrong.

  5. formatting the rowecho str_pad($name, 10) . number_format($price) . " USD\n";

    str_pad() pads each name to 10 characters so the prices line up in a column, and number_format() turns 1200 into 1,200.

You should see
Day 1
Day 2
Day 3
Stock sold out after 3 weeks
Laptop    1,200 USD
Mouse     25 USD
Keyboard  70 USD

foreach by value and by reference

In foreach ($prices as $price) the variable $price is a copy, so assigning to it does not change the prices in the array. Writing foreach ($prices as &$price) with an & makes $price an alias of the element, so every assignment lands directly in the array. The trap is that when the loop ends, $price still points at the last element, $prices[2]. If you leave it like that and later reuse a plain foreach ($prices as $price), every pass of that loop overwrites $prices[2] by itself.

reference-bug.php
<?php
$prices = [10, 20, 30];

// by value: $price is a copy, so the array stays the same
foreach ($prices as $price) {
    $price = $price * 2;
}
echo implode(", ", $prices), "\n";

// by reference: & makes $price an alias of each element
foreach ($prices as &$price) {
    $price = $price * 2;
}
echo implode(", ", $prices), "\n";

// $price is STILL a reference to $prices[2] here
foreach ($prices as $price) {
}
echo implode(", ", $prices), "\n";

unset($price); // break the link after any by-reference loop

The output is 10, 20, 30, then 20, 40, 60, then 20, 40, 40. In the last loop $prices[2] receives 20, then 40, then 40 again (the value it holds by then), so the 60 is lost. The defence is unset($price) after every by-reference loop. You can also avoid references altogether by writing back through the key, foreach ($prices as $i => $p) { $prices[$i] = $p * 2; }, or by using array_map().

break, continue and do-while

break ends the current loop at once, and continue skips the rest of the current pass and moves on to the next one. When loops are nested, the numbered forms matter: continue 2 jumps to the next pass of the outer loop and break 2 leaves both loops. In the script below, one zero-quantity line makes the whole order get skipped, and a full truck stops the outer loop.

break-continue.php
<?php
$orders = [
    ["id" => 101, "lines" => [2, 1, 4]],
    ["id" => 102, "lines" => [3, 0, 5]],
    ["id" => 103, "lines" => [1, 1]],
    ["id" => 104, "lines" => [6]],
];

$shipped = [];
foreach ($orders as $order) {
    foreach ($order["lines"] as $qty) {
        if ($qty === 0) {
            echo "Order {$order['id']} skipped: zero quantity\n";
            continue 2; // next ORDER, not the next line
        }
    }
    $shipped[] = $order["id"];
    if (count($shipped) === 2) {
        break; // the truck is full
    }
}
echo "Shipped: " . implode(", ", $shipped) . "\n";

$attempt = 10;
do {
    echo "do-while runs once even though 10 < 3 is false\n";
} while ($attempt < 3);

Order 102 is skipped, 101 and 103 ship, and because the truck is full order 104 is never looked at. The final do-while runs its body once even though $attempt < 3 is false from the start, which is why it fits retries and menu loops that must happen at least once. Avoid numbered break and continue beyond two levels: when you need more, moving the inner loop into a function and returning from it reads better.

Unpacking rows with list() and [ ] inside foreach

When each row is itself an array, you can unpack it in the foreach header instead of reading $row[0] and $row[1]. The form [$id, $name] takes values by position and ["id" => $id] takes them by key name. Leaving an empty slot, as in [$first, , $third], skips that position. The older list($a, $b) = ... spelling does the same thing. Asking for an index or key that does not exist gives Warning: Undefined array key and null.

unpack.php
<?php
$rows = [
    [1, "Aye", 85],
    [2, "Min", 72],
];
foreach ($rows as [$id, $name, $score]) {
    echo "#$id $name scored $score\n";
}

$users = [
    ["id" => 7, "email" => "aye@example.com"],
    ["id" => 9, "email" => "min@example.com"],
];
foreach ($users as ["id" => $id, "email" => $email]) {
    echo "$id: $email\n";
}

[$first, , $third] = ["a", "b", "c"];
echo $first . $third . "\n";

$a = 1;
$b = 2;
[$a, $b] = [$b, $a]; // swap without a temp variable
echo "$a $b\n";

This prints #1 Aye scored 85, #2 Min scored 72, then 7: aye@example.com and 9: min@example.com, then ac, then 2 1. For associative rows such as database results, unpacking by key keeps your code working even if the column order changes.

In real projects

Where this shows up in real projects

Roughly half of any PHP page is loops. A product list, a comment thread and every row of an admin table are foreach loops over arrays that came from a database. Inside HTML templates the alternative syntax, foreach (...): and endforeach;, is common because closing braces tend to get lost between the HTML tags. Every value you print must still go through htmlspecialchars().

template.php
<?php $products = ["Laptop", "Mouse <b>"]; ?>
<ul>
<?php foreach ($products as $product): ?>
  <li><?= htmlspecialchars($product, ENT_QUOTES, 'UTF-8') ?></li>
<?php endforeach; ?>
</ul>

Loops also live outside page rendering. Reading a large file with while (($line = fgets($handle)) !== false) handles one line at a time instead of loading everything into memory. A retry loop around an API call pairs a maximum attempt count with break. Pagination loops, cron jobs and batch imports follow the same shape. In production code, ask of every loop what makes it stop: an unbounded while can let a single request tie up a server for minutes.

Common mistakes

Common mistakes

1. Forgetting unset() after a by-reference loop

After foreach ($rows as &$row), $row still points at the last element. If later code reuses $row as if it were a fresh variable, for example in foreach ($other as $row), it silently rewrites that last row. No warning appears, which makes it hard to find. Write unset($row); right after the loop.

2. Editing the copy and expecting the array to change

foreach ($prices as $price) { $price *= 2; } leaves $prices untouched, because $price is a copy. To change the array, write back through the key ($prices[$i] = ...), use array_map(), or reach for & together with unset() only when you truly need a reference.

3. Off by one with <= count()

Array indexes start at 0 and end at count() - 1. With $i <= count($items) the last pass reads an index that does not exist and prints Warning: Undefined array key. Use $i < count($items), or better, use foreach.

4. Looping over something that is not an array

A function that fails often returns false or null instead of an array. Looping over that directly gives Warning: foreach() argument must be of type array|object, null given. Check the returned value before the loop, or fall back to an empty array with ?? [].

Best practices

Best practices

  • Reach for foreach first when walking an array, and use for with an index only when you really need the index.
  • For every while loop, ask what makes the condition false, and give retries a maximum attempt count.
  • When you use foreach (... as &$x), write unset($x); immediately after the loop.
  • Instead of heavily editing an array while looping over it, collect results into a new array and swap afterwards.

Mini challenge

Mini challenge: cinema seat checker

Write two functions that inspect a cinema seat map, where each row lists true for a sold seat and false for a free one. Find the first free seat and count the sold seats.

  • firstFreeSeat(array $seats): ?string returns the row letter plus a 1-based seat number such as "B2", or null when nothing is free
  • Leave both nested foreach loops with break 2 as soon as a free seat is found (no return inside the loops)
  • countTaken(array $seats): int skips free seats with continue and counts the sold ones
  • Print "sold out" for a hall whose seats are all taken
seats.php
<?php
function firstFreeSeat(array $seats): ?string
{
    // TODO: foreach over rows (row letter => cells), then over the cells
    // TODO: a free seat is false; build the label and leave BOTH loops
    return null;
}

function countTaken(array $seats): int
{
    // TODO: count only the true values, using continue for free seats
    return 0;
}

// TODO: build a 3-row seat map, then print the first free seat and the sold count
// TODO: test a hall that is completely sold out

Expected: First free seat: B2 Taken seats: 6 Full hall: sold out

Show hint

The row name is the array key, so write foreach ($seats as $row => $cells). The seat number is the index plus 1. Start $found as null, leave with break 2, and return $found after the loops. You can turn null into "sold out" with ?? when printing.

Show solution
seats.php
<?php
function firstFreeSeat(array $seats): ?string
{
    $found = null;
    foreach ($seats as $row => $cells) {
        foreach ($cells as $index => $taken) {
            if (!$taken) {
                $found = $row . ($index + 1);
                break 2;
            }
        }
    }
    return $found;
}

function countTaken(array $seats): int
{
    $count = 0;
    foreach ($seats as $cells) {
        foreach ($cells as $taken) {
            if (!$taken) {
                continue;
            }
            $count++;
        }
    }
    return $count;
}

$seats = [
    "A" => [true, true, true],
    "B" => [true, false, true],
    "C" => [false, false, true],
];
echo "First free seat: " . (firstFreeSeat($seats) ?? "sold out") . "\n";
echo "Taken seats: " . countTaken($seats) . "\n";

$full = ["A" => [true, true]];
echo "Full hall: " . (firstFreeSeat($full) ?? "sold out") . "\n";

Quick quiz 1 / 3

What does this code print? $n = [1, 2, 3]; foreach ($n as &$x) {} foreach ($n as $x) {} echo implode(', ', $n);

Quick quiz 2 / 3

What does this nested loop print? for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j === 2) continue 2; echo "$i$j "; } }

Quick quiz 3 / 3

After for ($i = 0; $i < 5; $i += 2) {} what does echo $i; show?

What to remember

  • Every loop needs a start, a stop and a step; if you cannot say what ends it, do not start writing it.
  • Use foreach for arrays, for for counting, while for waiting on a change and do-while for at-least-once work.
  • foreach by value edits a copy and leaves the array alone; after a by-reference loop, always unset() the variable.
  • break N and continue N steer nested loops, and [$a, $b] or list() unpacks rows right in the header.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Loops (While, For, Foreach) | Thuta Learning