For Loop
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
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
}
| Part | Runs | Purpose | Example |
|---|---|---|---|
| Initialization | Once, before the loop | Create the counter | $i = 1 |
| Condition | Before every iteration | Continue while true | $i <= 5 |
| Update | After every iteration | Move 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
$i = 1runs once.$i <= 5is checked: true, so the body runs.- After the body,
$i++increases$ito 2, and the condition is checked again. - When
$ibecomes 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 = 0and uses<(not<=) with the count. $n = count($fruits)is calculated once in the initialization rather than on every iteration in the condition.$i + 1produces 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
$dayruns from 0 to 6 — exactly seven iterations. modify("+$day day")returns a newDateTimeImmutablethat is$daydays after the start. The original$startis 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
forwhen the number of iterations is known or follows a numeric range. - Use
foreachto 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