Loops in PHP
for, while, do-while, and foreach — and when to reach for each one.
2 min read
PHP has four loop constructs, and picking the right one mostly comes down to whether you're counting, checking a condition, or iterating over a collection.
for: when you know how many times to loop
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration $i\n";
}The three parts — initialization, condition, increment — run in that order: set $i once, check the condition before every iteration, and run the increment after every iteration's body. for is the natural fit whenever a loop is driven by a counter.
while: loop while a condition holds
<?php
$attempts = 0;
while ($attempts < 3) {
echo "Attempt " . ($attempts + 1) . "\n";
$attempts++;
}The condition is checked before each iteration, including the first — if it's false immediately, the loop body never runs at all.
do-while: guarantee at least one run
<?php
$input = "";
do {
$input = readInput();
} while ($input === "");do-while checks its condition after the body runs, guaranteeing at least one iteration regardless of the condition's initial value — useful for something like "keep asking until we get valid input," where you need to ask at least once before there's anything to check.
foreach: the standard way to loop over an array
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo "$fruit\n";
}
$user = ["name" => "Amara", "role" => "admin"];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}foreach is by far the most common loop in everyday PHP — it iterates directly over an array's values (or, with as $key => $value, both keys and values) without needing to manage an index counter yourself. It works on both indexed and associative arrays identically.
break and continue
<?php
foreach ($fruits as $fruit) {
if ($fruit === "banana") {
continue; // skip this iteration
}
if ($fruit === "cherry") {
break; // stop the loop entirely
}
echo $fruit;
}continue skips the rest of the current iteration and moves to the next one; break exits the loop immediately, skipping any remaining iterations. Both work in every loop type covered in this lesson.
Modifying an array while looping over it by reference
<?php
$numbers = [1, 2, 3];
foreach ($numbers as &$number) {
$number *= 2;
}
unset($number); // break the reference after the loop
print_r($numbers); // [2, 4, 6]&$number makes $number a reference to each array element rather than a copy, so modifying it inside the loop modifies the original array. Always unset() the reference variable immediately after a foreach that uses & — leaving it alive is a well-known source of subtle bugs if the same variable name is reused in a later loop.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.