PHP Loops
PHP Loops: Repeating Tasks with foreach, for, and while
PHP loops run a block of code repeatedly until a condition turns false or every item in a collection is processed. Choosing the right loop keeps your code concise and prevents infinite-loop crashes.
Choosing the Right PHP Loop
Each loop fits a distinct iteration pattern in backend code.
| Loop Type | Best Use Case |
|---|---|
foreach |
Iterating over arrays, lists, and Traversable objects |
for |
Running a fixed number of indexed repetitions |
while |
Repeating while a dynamic condition or stream stays open |
do...while |
Running the body at least once before checking the condition |
<?php
declare(strict_types=1);
$cartItems = [
["name" => "USB-C Hub", "price" => 35.00],
["name" => "HDMI Cable", "price" => 12.50],
["name" => "Laptop Stand", "price" => 44.00],
];
$total = 0.0;
foreach ($cartItems as $index => $item) {
$total += $item['price'];
echo ($index + 1) . ". {$item['name']} - $" . number_format($item['price'], 2) . PHP_EOL;
}
echo "Cart Total: $" . number_format($total, 2) . PHP_EOL;
Controlling Loops with break, continue, and for
Use continue to skip the rest of the current iteration and break to exit the loop early once you find what you need.
<?php
declare(strict_types=1);
for ($attempt = 1; $attempt <= 5; $attempt++) {
if ($attempt === 2) {
continue; // Skip retry #2
}
echo "Checking service health (attempt {$attempt})" . PHP_EOL;
if ($attempt === 4) {
echo "Service healthy! Stopping retries." . PHP_EOL;
break;
}
}
Common Mistakes to Avoid
- Infinite
whileloops: Always update the condition variable inside the loop body, or ensure abreakcondition is reachable. - Calling
count($items)inside everyforcondition: Store$count = count($items);before the loop, or simply useforeach. - Leaving a reference active after
foreach ($arr as &$val): Always callunset($val);right after a by-referenceforeachso later variables do not overwrite the last array element.
Frequently Asked Questions
Which loop is fastest for arrays in PHP?
foreach is the cleanest and fastest way to traverse PHP arrays, because PHP arrays are ordered hash maps internally rather than plain C arrays.
When should I use do...while instead of while?
Use do...while when the loop body must run at least once before checking whether to repeat, such as polling a queue or generating a unique slug.
How do I break out of nested loops at once?
Pass a numeric level to break or continue, such as break 2; to exit both the inner and outer loop together.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.