← Back to PHP Course | Chapter 4: Control Flow | Lesson 12 of 14

PHP for Loop

What is a for Loop?

A for loop is the right tool when you know in advance how many times you need to repeat something. Its header packs three parts into one line — where the counter starts, the condition that keeps the loop going, and how the counter changes after each pass.

Example: What is a for Loop?

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

Custom Loop Steps

The step (increment) expression in a for loop's header isn't locked to adding 1 — you can add 2 to skip every other value, multiply for exponential steps, or use any expression at all, as long as it eventually makes the loop's condition become false.

Example: Custom Loop Steps

php
<?php
for ($i = 0; $i <= 10; $i += 2) {
    echo $i . "\n";
}
?>

Looping Through Indexed Arrays

Using the loop counter directly as an array index ($array[$i]) is exactly why for loops pair so naturally with arrays — you get both the current position and the corresponding value in every single iteration, without any extra bookkeeping.

Example: Looping Through Indexed Arrays

php
<?php
$fruits = ["apple", "banana", "cherry"];
for ($i = 0; $i < count($fruits); $i++) {
    echo $i . ": " . $fruits[$i] . "\n";
}
?>

Nested for Loops

One for loop nested inside another runs the inner loop to full completion for every single iteration of the outer one — the classic pattern for anything grid-shaped, like printing a multiplication table or walking a 2D array's rows and columns.

Example: Nested for Loops

php
<?php
for ($i = 1; $i <= 2; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        echo "$i x $j = " . ($i * $j) . "\n";
    }
}
?>

Alternative Syntax

PHP's alternative syntax swaps the opening { for a colon and the closing } for endfor;, which — exactly as with if and while — keeps a loop far more readable when its body is interleaved with HTML output in a template.

Example: Alternative Syntax

php
<?php for ($i = 1; $i <= 3; $i++): ?>
  <p>Row <?php echo $i; ?></p>
<?php endfor; ?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.