HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP For Loop

The for loop is used when you know in advance how many times the script should run. It gathers the initialization, condition, and increment logic into a single line, making your code extremely concise.


The for Loop Syntax

The for loop takes three parameters, separated by semicolons:

for (init counter; test counter; increment counter) {
  // code to be executed for each iteration;
}

Example Breakdown

<?php
    for ($x = 0; $x <= 10; $x++) {
        echo "The number is: $x <br>";
    }
?>
  • $x = 0; — Initializes the loop counter value.
  • $x <= 10; — The loop continues as long as this is true.
  • $x++; — Increases the counter value for each iteration.

Counting Backwards

You can also use the for loop to count down by using a decrement operator.

<?php
    for ($x = 10; $x >= 0; $x--) {
        echo "Countdown: $x <br>";
    }
?>

Loops with Custom Steps

The increment part doesn't have to be $x++. You can increase by any value you wish.

<?php
    for ($x = 0; $x <= 100; $x += 10) {
        echo "Step: $x <br>";
    }
?>
Technical Detail: Any of the three parameters in a for loop can be left empty (e.g., for (;;)), but you must still provide the semicolons.
Pro Tip: Use the for loop whenever the number of iterations is fixed, such as printing the days of a month or headers for a table.

Key Points to Remember

  • The for loop is ideal for a fixed number of repetitions.
  • It combines init, test, and update in one parentheses block.
  • Parameters are separated by semicolons, not commas.
  • You can count up or down and use custom step sizes (e.g., $x += 5).
  • It is one of the most performing and widely used loops in all of programming.