Skip to content

PHP Tutorial Loops

PHP for Loop

Lesson 94 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Use a for loop when you know how many times you want to repeat something.

index.php
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}
Output
OUTPUT
1 2 3 4 5

The three parts

Text
PLAIN
for (start; condition; step) { ... }
  1. Start ($i = 1): runs once, before the loop.
  2. Condition ($i <= 5): checked before each round. The loop continues while it is true.
  3. Step ($i++): runs after each round.

It is the same logic as a while loop, but with the counter handling written in one line.

Counting down

index.php
PHP
<?php
for ($i = 5; $i >= 1; $i--) {
    echo $i . " ";
}
echo "Lift off!";
Output
OUTPUT
5 4 3 2 1 Lift off!

Bigger steps

index.php
PHP
<?php
for ($i = 0; $i <= 20; $i += 5) {
    echo $i . " ";
}
Output
OUTPUT
0 5 10 15 20

Sum of numbers

index.php
PHP
<?php
$sum = 0;

for ($i = 1; $i <= 10; $i++) {
    $sum += $i;
}

echo "Sum: $sum";
Output
OUTPUT
Sum: 55

Looping over array positions

You can use for with an array when you need the index. Compute count() once, so PHP does not do it every round.

index.php
PHP
<?php
$names = ["Ana", "Ben", "Cara"];

for ($i = 0, $total = count($names); $i < $total; $i++) {
    echo ($i + 1) . ". " . $names[$i] . "\n";
}
Output
OUTPUT
1. Ana
2. Ben
3. Cara

If you do not need the index, foreach is simpler and safer.

Starting at 0 or 1

Array positions start at 0, so loops over arrays usually start at 0 and use < the length. Loops that count rounds for people usually start at 1 and use <=.

warning
Off-by-one errors
$i <= count($arr) goes one step too far and reads a position that does not exist. For arrays, use $i < count($arr).

Exercise: a times table

Print the 7 times table from 7 x 1 to 7 x 5, one per line, like 7 x 1 = 7.

Show a possible solution
index.php
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "7 x $i = " . (7 * $i) . "\n";
}
Output
OUTPUT
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35