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
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
1. Which PHP loop is guaranteed to execute its body at least once?
2. By default, does foreach modify the original array when you change the loop variable?
3. Why should you call unset($value) after a foreach loop that used &$value?
4. What does continue do inside a loop?
5. Which loop type is most idiomatic for iterating over an associative array's keys and values?
Was this page helpful?
You May Also Like
Conditionals in PHP
Covers if/elseif/else, the ternary and null-coalescing shortcuts, switch statements, and alternative control-structure syntax used in templates.
Indexed and Associative Arrays
Understand PHP's single array type used for both ordered lists and key-value maps, including creation, iteration, and common manipulation patterns.
Array Functions
Survey PHP's extensive standard-library array functions for transforming, filtering, searching, and reducing arrays without manual loops.
Functions in PHP
Learn how PHP functions are declared, typed, and invoked, including default parameters, variadics, references, and closures for reusable logic.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics