PHP Loops

JA JASWANT Updated 17 Oct 2026
6 min read ·Lesson 5 of 248
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
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

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

Signed-in readers only.