← Back to PHP Course | Chapter 4: Control Flow | Lesson 9 of 14

PHP Loops

Without loops, running the same piece of code 100 times would mean writing it out 100 times. A loop lets you repeat a block of code automatically, either a fixed number of times, until a condition becomes false, or once for every item in a collection -- turning a tedious, error-prone copy-paste job into a few lines that scale to any amount of data.

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
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Hello\n";
}
?>

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
<?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"; }
?>

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
<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) continue;
    if ($i == 5) break;
    echo $i . "\n";
}
?>

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
<?php
$i = 0;
while ($i < 5) {
    echo $i . "\n";
    $i++; // without this line, the loop would never end
}
?>

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
<?php
$items = ["apple", "banana", "cherry"];
foreach ($items as $item) {
    echo $item . "\n";
}
?>
Common Mistakes
  1. Writing a loop condition that never becomes false, creating an infinite loop that hangs the script or exhausts server resources.
  2. 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.
  3. 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.
Chapter Summary
  • 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.
Browser Support

All four PHP loop types have been part of the language since its earliest versions and behave identically across every environment.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.