PHP For Loop Example

Repeat code a fixed number of times with a for loop. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
1 2 3 4 5
5 4 3 2 1
0 2 4 6 8 10 

How this for loop example works

A for loop has three parts: initialisation ($i = 1), a condition checked before each iteration ($i <= 5) and an update run after each iteration ($i++). Use it when you know how many times to repeat; use foreach to walk through arrays.

break and continue

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 === 0) {
        continue; // skip even numbers
    }
    if ($i > 7) {
        break;    // stop the loop
    }
    echo "$i ";
}

Output:

1 3 5 7