PHP Loops
In this page:
Why Loops Exist
A loop repeats a block of code automatically instead of you writing that code out multiple times by hand -- printing "Hello" 5 times, processing every row from a database query, or validating every field in a submitted form are all naturally loop-shaped problems.
Note: Whenever you notice yourself about to copy-paste a block of nearly identical code several times, that is a strong signal a loop belongs there instead.
Warning: A loop with no exit condition, or one whose exit condition can never actually be met, runs forever and will eventually crash or time out the script.
Example: Why Loops Exist
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Hello\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
The Four PHP Loop Types at a Glance
while runs as long as a condition stays true, checking that condition before every pass. do-while works the same way but checks after each pass, guaranteeing the body runs at least once. for is built for a known, countable number of repetitions. foreach is purpose-built to walk through every element of an array automatically.
Note: Reach for foreach by default whenever you are iterating an array -- it handles the counting and indexing for you and is far less error-prone than a manual for loop over array keys.
Warning: Using for or while to manually walk an array (with an index variable) instead of foreach is more work and more error-prone than necessary for that specific job.
Example: The Four PHP Loop Types at a Glance
<?php
$i = 0;
while ($i < 2) { echo "while\n"; $i++; }
$j = 0;
do { echo "do-while\n"; $j++; } while ($j < 2);
for ($k = 0; $k < 2; $k++) { echo "for\n"; }
foreach (["a", "b"] as $v) { echo "foreach: $v\n"; }
?>
Login to try C/C++/Java/PHP code in the editor
Loop Control: break and continue
Inside any loop, break immediately exits the loop entirely, skipping all remaining iterations, while continue skips just the rest of the current iteration and moves on to the next one -- both give you fine control over a loop's flow beyond its basic exit condition.
Note: Use break to stop searching once you have found what you need, and continue to skip irrelevant items without processing the rest of that one iteration.
Warning: break only exits the single loop it is directly inside; in nested loops, it does not automatically exit an outer loop too, unless you pass a numeric level to break.
Example: Loop Control: break and continue
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
if ($i == 5) break;
echo $i . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Avoiding Infinite Loops
An infinite loop happens when a loop's condition never becomes false -- most often because the code forgets to update the variable the condition depends on, or updates it in a way that can never actually satisfy the exit condition.
Note: Before running a new while or for loop, double check that every path through the loop body actually moves the condition closer to becoming false.
Warning: An infinite loop in a web request will typically run until the server's execution time limit kills the script, wasting resources and potentially leaving the request hanging.
Example: Avoiding Infinite Loops
<?php
$i = 0;
while ($i < 5) {
echo $i . "\n";
$i++; // without this line, the loop would never end
}
?>
Login to try C/C++/Java/PHP code in the editor
Choosing the Right Loop for the Job
Pick while when you don't know in advance how many times you'll repeat but do know the stopping condition; pick do-while when the body must run at least once regardless; pick for when you know exactly how many repetitions you need, often with a counter; pick foreach whenever you are iterating an array's elements.
Note: When in doubt between for and foreach for array iteration specifically, foreach is almost always the better, safer default.
Warning: Using the wrong loop type does not usually cause a bug by itself, but it often makes the code noticeably harder to read and more error-prone to maintain than the loop type built for that exact job.
Example: Choosing the Right Loop for the Job
<?php
$items = ["apple", "banana", "cherry"];
foreach ($items as $item) {
echo $item . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
- Writing a loop condition that never becomes false, creating an infinite loop that hangs the script or exhausts server resources.
- Choosing the wrong loop type for the job -- like a while loop for iterating a known array, when foreach is purpose-built and far less error-prone for that exact case.
- Forgetting to update the loop's counter or condition variable inside the loop body, which is the single most common cause of an infinite while or for loop.
- PHP offers four loop types: while, do-while, for, and foreach -- each suited to a different kind of repetition.
- while checks its condition before each pass; do-while checks it after, guaranteeing at least one run.
- for is built for counting a known number of repetitions; foreach is purpose-built for walking through every item in an array.
All four PHP loop types have been part of the language since its earliest versions and behave identically across every environment.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: