Back to course

The for Loop

PHP: The Complete 0 to Hero Bootcamp

14. The for Loop

The for loop is typically used when you know exactly how many times you want to iterate, or when managing a simple numerical counter.

for Loop Structure

It consists of three parts, separated by semicolons, inside the parentheses:

  1. Initialization: Executed once at the start (e.g., $i = 0).
  2. Condition: Evaluated before each iteration. The loop continues if true.
  3. Increment/Decrement: Executed after each iteration (e.g., $i++).

php

<?php echo "<h2>Counting Up:</h2>"; for ($i = 1; $i <= 10; $i++) { echo "Number: " . $i . "<br>"; } echo "<h2>Counting Down:</h2>"; for ($j = 10; $j >= 0; $j--) { echo "Countdown: " . $j . "<br>"; } ?>

Nested for Loops

Loops can be placed inside other loops. This is often used to iterate over multi-dimensional data or create structures like grids or multiplication tables.

php

<?php // Example: Simple grid output for ($row = 1; $row <= 3; $row++) { for ($col = 1; $col <= 3; $col++) { echo "($row,$col) "; } echo "<br>"; } ?>

When to use for: Best suited for fixed iterations where the counter logic is clear and simple.