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

Counting Up:"; for ($i = 1; $i <= 10; $i++) { echo "Number: " . $i . "
"; } echo "

Counting Down:

"; for ($j = 10; $j >= 0; $j--) { echo "Countdown: " . $j . "
"; } ?>

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

"; } ?>

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