Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP for loop

Reference for the PHP for loop: initializer, condition and step expressions, multiple counters, omitting parts, nested loops and common off-by-one mistakes.

for is the counter loop. Its header holds three expressions separated by semicolons: one that runs once before the loop, one that is tested before each pass, and one that runs after each pass. It is the natural choice when you know how many times to repeat, or when you need the index.

Each of the three parts may contain several comma-separated expressions, or be left empty.

PHP
for ($i = 0; $i < 3; $i++) {
    echo $i;
}

Try it

PHP Counting up, down and in steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Nested loops and omitted parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
for (initialization; condition; step) {
    // body
}

for (initialization; condition; step):
    // body
endfor;
Name Description
initialization Zero or more comma-separated expressions, run once before the first test.
condition Zero or more comma-separated expressions evaluated before each pass; the value of the last one decides. An empty condition counts as true.
step Zero or more comma-separated expressions, run after each pass.

Return value: none; for is a statement.

Usage notes

  • Order of events: initialization, then condition, body, step, condition, body, step, and so on. The step runs after the body (and after continue).
  • Off-by-one errors. Arrays start at index 0, so loop with $i < count($a), not <=.
  • for (;;) is an infinite loop; leave it with break or return.
  • Caching the length. count() is cheap, but putting it in the initializer ($n = count($a)) avoids repeated calls and makes it explicit that you do not expect the array to change.
  • The counter survives the loop. $i still exists afterwards, holding the first value that failed the condition.
  • Floating-point counters accumulate error (for ($x = 0; $x != 1; $x += 0.1) may never end). Use an integer counter and divide.
  • Arrays with gaps or string keys need foreach; $a[$i] fails on missing keys.
  • Don't modify the counter inside the body unless you have a good reason; it confuses readers.
  • Skipping and stopping: see break and continue.