For Loop

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 57 of 255

What Is a for Loop?

In simple terms: A for loop repeats code a specific number of times. You set where a counter starts, when it stops, and how it changes — all in one line.

Technically: The for loop has a header with three expressions: an initialization that runs once, a condition checked before every iteration, and an update that runs after every iteration. It is the most compact way to write a counting loop.

Why It Is Needed

When the number of repetitions is known — or depends on a numeric range — a for loop keeps all the counter logic in one place:

for ($i = 1; $i <= 5; $i++) { ... }

Compare this to a while loop, where the same three parts are spread across separate lines. With for, a reader immediately sees the start, the end, and the step.


Syntax

for (initialization; condition; update) {
    // code to repeat
}
PartRunsPurposeExample
InitializationOnce, before the loopCreate the counter$i = 1
ConditionBefore every iterationContinue while true$i <= 5
UpdateAfter every iterationMove the counter$i++

Flow

initialization
      │
      ▼
 ┌─────────────┐  false
 │ condition ? │────────► continue after the loop
 └─────┬───────┘
     true
       ▼
   loop body
       │
       ▼
    update ────► back to condition

Example

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Row $i\n";
}

Output

Row 1
Row 2
Row 3
Row 4
Row 5

How It Works

  1. $i = 1 runs once.
  2. $i <= 5 is checked: true, so the body runs.
  3. After the body, $i++ increases $i to 2, and the condition is checked again.
  4. When $i becomes 6, the condition is false and the loop ends.

After the loop, $i still exists and holds 6. PHP has no block scope, so loop variables remain available after the loop.


Counting Patterns

Counting Down

<?php
for ($i = 5; $i >= 1; $i--) {
    echo $i . ' ';
}
echo "\n";

Output

5 4 3 2 1 

Steps Other Than 1

<?php
for ($percent = 0; $percent <= 100; $percent += 25) {
    echo "$percent% ";
}
echo "\n";

for ($i = 10; $i >= 0; $i -= 2) {
    echo $i . ' ';
}
echo "\n";

Output

0% 25% 50% 75% 100% 
10 8 6 4 2 0 

The update expression can be any assignment, such as += 25 or -= 2.

Multiple Expressions

Each part of the header can contain several expressions separated by commas:

<?php
for ($left = 0, $right = 10; $left < $right; $left += 3, $right -= 3) {
    echo "left = $left, right = $right\n";
}

Output

left = 0, right = 10
left = 3, right = 7

Two counters move toward each other. After the second iteration, $left becomes 6 and $right becomes 4, so $left < $right is false. (When the condition part contains several comma-separated expressions, only the last one decides whether the loop continues — use && instead to avoid confusion.)


Looping Over Indexed Arrays

A for loop can walk through an array with numeric keys 0, 1, 2, …:

<?php
$fruits = ['Mango', 'Banana', 'Guava'];

for ($i = 0, $n = count($fruits); $i < $n; $i++) {
    echo ($i + 1) . ". {$fruits[$i]}\n";
}

Output

1. Mango
2. Banana
3. Guava

Why It Is Written This Way

  • Array indexes start at 0, so the loop starts at $i = 0 and uses < (not <=) with the count.
  • $n = count($fruits) is calculated once in the initialization rather than on every iteration in the condition.
  • $i + 1 produces human-friendly numbering starting at 1.

For simply visiting every element, foreach is clearer and works with any keys. for is useful when you need the index for calculations — such as stepping through every second element, comparing neighbors, or iterating backwards.

Iterating Backwards

<?php
$history = ['Page A', 'Page B', 'Page C'];

for ($i = count($history) - 1; $i >= 0; $i--) {
    echo "Back to: {$history[$i]}\n";
}

Output

Back to: Page C
Back to: Page B
Back to: Page A

The last index is count - 1, because indexes start at 0.


Empty Header Parts

Any of the three parts can be left empty. An empty condition is treated as true, so for (;;) is an infinite loop — equivalent to while (true) — and needs a break:

<?php
$attempt = 0;

for (;;) {
    $attempt++;

    if ($attempt === 3) {
        echo "Stopped after $attempt attempts\n";
        break;
    }
}

Output

Stopped after 3 attempts

while (true) expresses the same idea more readably and is more common.


Practical Example: Next 7 Days

<?php
$start = new DateTimeImmutable('2026-10-09');

for ($day = 0; $day < 7; $day++) {
    $date = $start->modify("+$day day");
    $label = $day === 0 ? ' (today)' : '';

    echo $date->format('D d M') . $label . "\n";
}

Output

Fri 09 Oct (today)
Sat 10 Oct
Sun 11 Oct
Mon 12 Oct
Tue 13 Oct
Wed 14 Oct
Thu 15 Oct

How It Works

  • The counter $day runs from 0 to 6 — exactly seven iterations.
  • modify("+$day day") returns a new DateTimeImmutable that is $day days after the start. The original $start is never changed.
  • format('D d M') produces a short weekday, the day of the month, and a short month name.

This pattern is used for date pickers, delivery slot selection, and calendars.


Practical Example: Quantity Price Table

<?php
$unitPrice = 250;

printf("%-5s %-10s %s\n", 'Qty', 'Discount', 'Total');

for ($qty = 1; $qty <= 5; $qty++) {
    $discountPercent = $qty >= 5 ? 15 : ($qty >= 3 ? 10 : 0);
    $total = $qty * $unitPrice * (100 - $discountPercent) / 100;

    printf("%-5d %-10s ₹%s\n", $qty, $discountPercent . '%', number_format($total, 2));
}

Output

Qty   Discount   Total
1     0%         ₹250.00
2     0%         ₹500.00
3     10%        ₹675.00
4     10%        ₹900.00
5     15%        ₹1,062.50

Each iteration calculates one row of the table for a quantity from 1 to 5. The nested ternary is parenthesized, as PHP 8 requires.


Common Mistakes

Off-by-One With Array Indexes

<?php
$items = ['A', 'B', 'C'];

for ($i = 0; $i <= count($items); $i++) {
    echo $items[$i];
}

Output

ABC
PHP Warning:  Undefined array key 3 in /path/script.php on line 5

<= runs one iteration too many. Use < with the count, or use foreach.

Using Floats as Loop Counters

for ($x = 0; $x != 1; $x += 0.1) { ... }

Effect: 0.1 cannot be represented exactly, so $x never equals 1 exactly — this loop never ends.

Fix: Count with integers and calculate the float inside the loop: for ($i = 0; $i <= 10; $i++) { $x = $i / 10; ... }.

Changing the Counter Inside the Body

Effect: Skipped or repeated iterations that are hard to follow.

Fix: Change the counter only in the update part of the header.

Calling Expensive Functions in the Condition

Effect: The function runs on every iteration.

Fix: Calculate the value once in the initialization ($i = 0, $n = count($items)).

Using for With Associative Arrays

Effect: Numeric keys do not exist, causing warnings.

Fix: Use foreach.


Best Practices

  • Use for when the number of iterations is known or follows a numeric range.
  • Use foreach to iterate over arrays unless you need index arithmetic.
  • Count with integers; compute floats from the counter.
  • Use < with zero-based counts to avoid off-by-one errors.
  • Keep the header simple — one counter, one condition, one update — whenever possible.

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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home 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 Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting 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 PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 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 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 AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about For Loop and get answers drawn from it.

Signed-in readers only.