100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
PHP

Loops in PHP

Explains PHP's for, while, do-while, and foreach loops, along with break, continue, and reference-based iteration pitfalls.

Control FlowBeginner8 min readJul 9, 2026
Analogies

Loops in PHP

PHP provides four looping constructs: for (counter-based, ideal when you know the iteration count or need explicit index control), while (condition-checked before each iteration), do-while (condition-checked after, guaranteeing at least one execution), and foreach (iterates over arrays and any Traversable object, and is by far the most commonly used loop in idiomatic PHP for collection processing). Each supports break to exit the loop entirely and continue to skip to the next iteration, both of which can take an optional numeric argument to affect an outer loop when nested.

🏏

Cricket analogy: A bowler runs a fixed 'for' number of deliveries per over, keeps bowling 'while' the captain says continue, always bowls at least one over 'do-while' on debut, and 'foreach' batter faced adjusts the field, with a wicket letting the captain 'break' the spell or 'continue' to the next over.

foreach and Iterating by Reference

foreach ($array as $key => $value) is the idiomatic way to walk both indexed and associative arrays. By default, $value is a copy of each element, so modifying it inside the loop does not change the original array. Adding an ampersand — foreach ($array as &$value) — iterates by reference, letting you mutate the array in place, but this comes with a well-known trap: the reference variable persists after the loop ends and can silently corrupt later code that reuses the same variable name, so best practice is to unset($value) immediately after such a loop.

🏏

Cricket analogy: Reviewing a batter's shot 'by value' is like watching a replay copy — critiquing it changes nothing about the real shot played — while coaching them live 'by reference' directly changes their technique, but a coach must consciously reset focus or leftover cues bleed into the next player's session.

php
<?php
declare(strict_types=1);

$inventory = ['apples' => 12, 'pears' => 4, 'plums' => 0];

// foreach with key and value
foreach ($inventory as $fruit => $count) {
    if ($count === 0) {
        continue; // skip out-of-stock items
    }
    echo "{$fruit}: {$count}\n";
}

// modifying in place requires a reference
foreach ($inventory as &$count) {
    $count += 1; // restock everything by 1
}
unset($count); // break the reference to avoid later bugs

// classic counted loop
for ($i = 0, $sum = 0; $i < 5; $i++) {
    $sum += $i;
}

$attempts = 0;
do {
    $attempts++;
} while ($attempts < 3);

echo "Sum: {$sum}, Attempts: {$attempts}\n";

do-while is the only PHP loop guaranteed to run its body at least once, since the condition is evaluated after the first pass — useful for retry logic or 'read input, then check if you should stop' patterns.

After a foreach loop that iterates by reference (&$value), the loop variable keeps pointing at the last array element. A second foreach reusing the same variable name without unset() can overwrite the array's last element unexpectedly — always unset($value) right after a by-reference foreach.

  • for is best for counter-driven iteration; while checks the condition before each pass; do-while checks after.
  • foreach is the idiomatic way to iterate arrays and Traversable objects, supporting both value-only and key => value forms.
  • foreach copies each value by default; use &$value to mutate the original array in place.
  • Always unset() a by-reference foreach loop variable immediately after the loop to avoid stale-reference bugs.
  • break exits a loop entirely; continue skips to the next iteration; both accept an optional level for nested loops.
  • do-while guarantees the loop body executes at least once, unlike for/while/foreach.

Practice what you learned

Was this page helpful?

Topics covered

#PHP#PHPProgrammingStudyNotes#Programming#LoopsInPHP#Loops#Foreach#Iterating#Reference#StudyNotes#SkillVeris