PHP For Loop

PHP For Loop

The for loop is used when you know in advance how many times the script should run.

1 - Syntax

for (init; condition; increment) {
    // code to execute
}

2 - Basic Example

for ($i = 0; $i < 5; $i++) {
    echo "Item $i <br>";
}

3 - Counting Down

for ($i = 10; $i >= 1; $i--) {
    echo "$i... ";
}
echo "Go!";

4 - Looping Through an Indexed Array

$colors = ["Red", "Green", "Blue"];
for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . "<br>";
}

5 - Nested For Loop

for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        echo "$i x $j = " . ($i * $j) . "<br>";
    }
}

Note: All three parts of the for loop (init, condition, increment) are optional, but the semicolons must always be present.

-Tip-