The for loop in PHP is a versatile tool for running a block of code a specified number of times. It’s ideal when the number of iterations is predetermined.
Syntax
PHP
x
for (initialization; condition; increment) {
// code block
}
- Initialization: Executes once at the start, setting the initial state.
- Condition: Checked before every iteration; the loop runs as long as this evaluates to
true
. - Increment: Executes after each iteration, often used to update the counter variable.
Example: Motorcycle Model Numbers
This example displays motorcycle model numbers from 0 to 10:
PHP
for ($model = 0; $model <= 10; $model++) {
echo "Motorcycle model: $model <br>";
}
Explanation:
$model = 0;
initializes the counter variable$model
to 0, establishing the starting point of the loop.$model <= 10;
checks whether the value of$model
is less than or equal to 10 before each iteration. If true, the loop proceeds; otherwise, it stops.$model++;
increments the counter variable$model
by 1 after each loop iteration, allowing the loop to advance towards its stopping point.
This ensures that the script outputs all motorcycle model numbers from 0 to 10 in sequence.
The break Statement
The break statement can be used to terminate the loop early. For instance, stop the loop when the motorcycle model reaches 3:
PHP
for ($model = 0; $model <= 10; $model++) {
if ($model == 3) break;
echo "Motorcycle model: $model <br>";
}
The continue Statement
The continue statement allows skipping the current iteration and moving on to the next. In this example, skip the model corresponding to Honda (represented as 3):
PHP
for ($model = 0; $model <= 10; $model++) {
if ($model == 3) continue;
echo "Motorcycle model: $model <br>";
}
Custom Increment Steps
You can modify the increment value to suit specific needs. For example, count motorcycle production batches in steps of 10:
PHP
for ($batch = 0; $batch <= 100; $batch += 10) {
echo "Production batch: $batch <br>";
}