for Loop

Loop a specific number of times using a counter.

Syntaxfor ($i = 0; $i < 10; $i++) { // code }

The for loop is ideal when you know in advance how many times you want to repeat. It has three parts inside the parentheses, separated by semicolons:

  1. Initialization — set a counter.
  2. Condition — test before each pass.
  3. Increment — update the counter after each pass.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Render a numbered list of search results by iterating with a for loop from 1 to count($results).
  • Pad an array to a fixed length by using a for loop to append default values.
  • Generate a fixed number of unique random coupon codes in a for loop.

More examples

Basic for loop

for consists of initialiser, condition, and increment — all three in one line for precise iteration control.

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

Iterating over an indexed array

A for loop with count() is the standard way to iterate an indexed array when the position number matters.

Example · php
<?php
$results = ['Alpha', 'Beta', 'Gamma', 'Delta'];
$count   = count($results);

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

Reverse and step iteration

The increment expression can decrement or step by any amount, enabling countdowns and sparse-index traversal.

Example · php
<?php
// Countdown
for ($i = 10; $i >= 1; $i--) {
    echo "$i... ";
}
echo "Go!\n";

// Every second item
$items = range(0, 10);
for ($i = 0; $i < count($items); $i += 2) {
    echo $items[$i] . ' ';
}

Discussion

  • Be the first to comment on this lesson.