PHP For Loop
A for loop repeats a block of code for a counted number of rounds. Its counter moves in steps until a test turns false.
Counting from 0 to 4
The counter starts at 0. The loop prints each value up to 4.
<?php
for ($i = 0; $i <= 4; $i++) {
echo $i . "\n";
}A step of 2
The step adds 2 after each round. The printed values jump by two each time.
<?php
for ($i = 0; $i <= 8; $i += 2) {
echo $i . "\n";
}A sum built in a for loop
The total starts at 0. Each round adds the counter to the total, and the sum prints after the loop.
<?php
$total = 0;
for ($i = 1; $i <= 5; $i++) {
$total += $i;
}
echo $total . "\n";Example
<?php
for ($i = 2; $i <= 10; $i += 2) {
echo $i . "\n";
}Key points
- The for header holds the start, the test and the step in one line.
- The start sets the counter before the first round.
- The test runs before each round.
- The step runs after each round and changes the counter.
- A for loop suits a job with a counted number of rounds.
In this example, the counter starts at 2. The step adds 2 after each round. The loop prints the even numbers from 2 to 10, one per line.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
In a for header, what runs after each round?