A for loop is a control structure used to repeat a block of code a specific number of times.
It is ideal when you can determine the loop's boundary—either by using a hardcoded number or by calculating a dynamic count (such as checking the size of an array) right as the loop begins.
The syntax of a for loop packs three distinct expressions inside the parentheses (), separated by semicolons ;. The code you want to repeat lives inside the curly braces { ... }.
<?php
for (initializer; condition; increment) {
// Code to repeat
}
The Three Expressions:
Initializer Runs exactly once before the loop begins. It sets up a counter variable (typically named $i).
Condition Checked before every single loop iteration. If it evaluates to true, the loop runs. If it evaluates to false, the loop stops immediately.
Increment / Decrement: Runs at the very end of every iteration, changing the counter variable so the loop can eventually finish.
This example uses a fixed number to count from 1 to 5:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "The count is: " . $i;
}
count())A for loop is perfectly applicable to dynamic data.
Here, we use count() to dynamically determine how many times the loop should run based on how many elements are inside the array:
<?php
$fruits = ["Apple", "Banana", "Orange"]; // An indexed array
$totalFruits = count($fruits); // Dynamically counts the elements (3)
for ($i = 0; $i < $totalFruits; $i++) {
// Uses the counter $i to access each array element by its index
echo "Fruit: " . $fruits[$i];
}
The Setup: PHP evaluates the initializer (e.g., setting $i = 0).
The Evaluation: PHP checks the condition (is $i less than the total count?). If true, it runs the code inside the curly braces.
The Step: After executing the block, PHP runs the increment ($i++) to move the counter forward, then jumps back to step 2.
The Exit: As soon as the condition evaluates to false, PHP instantly exits the loop and continues running any code written below it.