PHP Loops

JA JASWANT Updated 17 Oct 2026
6 min read ·Lesson 5 of 11
In this post

What Is a Loop? In simple terms: A loop repeats a block of code several times — for example, once for every product in a cart, once for every line in a file, or until a condition is no longer true. Te

What Is a Loop?

In simple terms: A loop repeats a block of code several times — for example, once for every product in a cart, once for every line in a file, or until a condition is no longer true.

Technically: A loop is a control structure that executes a block of statements repeatedly. Each repetition is called an iteration. The loop continues while a condition holds or until every element of a collection has been processed.

Why Loops Are Needed

Without loops, repeating work means repeating code:

echo "Lesson 1\n";
echo "Lesson 2\n";
echo "Lesson 3\n";
// ... and so on for every lesson

This does not scale, and it cannot handle data whose size is unknown in advance — such as the rows returned from a database or the items in a user's cart. A loop writes the work once and applies it as many times as needed:

<?php
for ($lesson = 1; $lesson <= 3; $lesson++) {
    echo "Lesson $lesson\n";
}

Output

Lesson 1
Lesson 2
Lesson 3

Loop Types in PHP

LoopRepeatsCondition CheckedTypical Use
whileWhile a condition is trueBefore each iterationUnknown number of repetitions (reading until data runs out, retrying)
do...whileWhile a condition is trueAfter each iterationThe body must run at least once (prompts, paginated fetching)
forA counted number of timesBefore each iterationKnown number of repetitions, numeric ranges
foreachOnce per element— (stops after the last element)Arrays and iterable objects — the most common loop in PHP

Each loop has its own lesson: While Loop, Do While Loop, For Loop, and Foreach Loop.


The Same Task With Each Loop

Printing the numbers 1 to 5 shows how the loops differ in structure:

<?php
// while
$i = 1;
while ($i <= 5) {
    echo $i . ' ';
    $i++;
}
echo "\n";

// do...while
$i = 1;
do {
    echo $i . ' ';
    $i++;
} while ($i <= 5);
echo "\n";

// for
for ($i = 1; $i <= 5; $i++) {
    echo $i . ' ';
}
echo "\n";

// foreach
foreach ([1, 2, 3, 4, 5] as $number) {
    echo $number . ' ';
}
echo "\n";

Output

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

All four produce the same result, but notice where the counter is managed:

  • while and do...while: you initialize, test, and update the counter in separate places.
  • for: initialization, test, and update are together in the loop header.
  • foreach: there is no counter at all — PHP moves through the array for you.

Anatomy of a Counting Loop

Most loops that count have four parts:

initialization  →  condition  →  body  →  update  ─┐
                        ▲                          │
                        └──────────────────────────┘
          (when the condition is false, the loop ends)
PartExamplePurpose
Initialization$i = 1Set the starting state
Condition$i <= 5Decide whether to run another iteration
Bodyecho $i;The work repeated each time
Update$i++Move toward the end condition

If the update is missing — or never makes the condition false — the loop runs forever.


Infinite Loops

An infinite loop never ends because its condition never becomes false:

$i = 1;
while ($i <= 5) {
    echo $i;
    // forgot $i++ — $i is always 1
}

On a web server, an infinite loop runs until PHP's max_execution_time limit (30 seconds by default for web requests) stops the script with a fatal error. In the command line, there is no time limit by default, so the script runs until you press Ctrl + C.

Some programs use intentional infinite loops — for example, a queue worker that waits for jobs — but they always contain a break or return that ends the loop under specific conditions:

while (true) {
    $job = getNextJob();
    if ($job === null) {
        break;
    }
    process($job);
}

Controlling Loops: break and continue

StatementEffect
breakLeaves the loop immediately
continueSkips the rest of the current iteration and starts the next one
<?php
foreach ([4, 0, 7, -1, 9] as $value) {
    if ($value === 0) {
        continue;   // skip zeros
    }

    if ($value < 0) {
        break;      // stop at the first negative number
    }

    echo $value . "\n";
}

Output

4
7

0 is skipped, and the loop ends when -1 is reached, so 9 is never processed. Both statements have their own lessons: Break Statement and Continue Statement.


Choosing the Right Loop

SituationBest Choice
Process every element of an arrayforeach
Repeat an exact number of times, or loop over a numeric rangefor
Repeat until something happens (data runs out, condition met)while
Run the body at least once, then decide whether to repeatdo...while
Transform, filter, or total an arrayOften an array function instead of a loop

Loops vs Array Functions

Many common loops can be replaced with built-in functions that express intent directly:

<?php
$prices = [499, 1299, 89, 2499];

// Loop
$total = 0;
foreach ($prices as $price) {
    $total += $price;
}
echo "Loop total: $total\n";

// Array function
echo "array_sum total: " . array_sum($prices) . "\n";

$affordable = array_filter($prices, fn($p) => $p < 1000);
echo "Under ₹1000: " . implode(', ', $affordable) . "\n";

Output

Loop total: 4386
array_sum total: 4386
Under ₹1000: 499, 89

array_sum(), array_filter(), array_map(), and similar functions are covered in the PHP Arrays section. Loops remain the right tool when each iteration does several things, needs early exits, or produces output.


Loops in Templates

In HTML templates, loops use the alternative syntax:

<?php $courses = ['PHP Basics', 'MySQL', 'Laravel']; ?>
<ul>
<?php foreach ($courses as $course): ?>
    <li><?= htmlspecialchars($course) ?></li>
<?php endforeach; ?>
</ul>

Output (HTML)

<ul>
    <li>PHP Basics</li>
    <li>MySQL</li>
    <li>Laravel</li>
</ul>

See Alternative Syntax.


Performance Tips

  • Do not repeat expensive work in the loop condition. In for ($i = 0; $i < count($items); $i++), count() runs on every iteration. Store it once: for ($i = 0, $n = count($items); $i < $n; $i++). (count() on arrays is fast, but the habit matters for slower functions.)
  • Avoid database queries inside loops. Running one query per item (the "N+1 query problem") is a common cause of slow pages. Fetch all needed data with one query before the loop.
  • Be careful with nested loops over large data. Two nested loops over 10,000 items each perform 100 million iterations. Use lookup arrays instead (see Nested Loops).

Common Mistakes

Forgetting to Update the Loop Variable

Effect: Infinite loop.

Fix: Make sure every iteration moves toward the end condition.

Off-by-One Errors

Effect: One iteration too many or too few (for example, <= instead of < when indexing arrays from 0).

Fix: Use foreach for arrays; for counting loops, check the first and last iteration explicitly.

Using for to Iterate Associative Arrays

Effect: Numeric indexes do not exist in associative arrays, causing "Undefined array key" warnings.

Fix: Use foreach.

Modifying an Array While Looping Over It With Indexes

Effect: Skipped or repeated elements.

Fix: Build a new array, or use foreach (which works on a copy unless you loop by reference).


Best Practices

  • Use foreach for arrays; it is clearer and avoids index errors.
  • Use for for counted repetition and while for "until" conditions.
  • Keep loop bodies short; move complex work into functions.
  • Never run queries or remote API calls inside a loop when one batched call can fetch the data.
  • Consider array functions for simple transformations and totals.

Official reference: https://www.php.net/manual/en/language.control-structures.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Loops and get answers drawn from it.

Signed-in readers only.