The for loop
Learn to write operations that repeat a fixed number of times with the for loop.
The for loop
The for loop is used to repeat an action a fixed number of times. It has three parts: a starting value, a condition and an increment. These parts are separated by semicolons and written inside parentheses.
For example, for ($i = 1; $i <= 3; $i++) makes $i start at 1, grow by 1 each step and keep looping while it is 3 or less. The loop body goes inside curly braces.
Counter and step
The counter is the variable that tracks which step the loop is on; it is usually named $i. In the increment part you can increase it by one with $i++.
You can also count down: for ($i = 3; $i >= 1; $i--) runs the loop for 3, then 2, then 1. To change the step size you can use compound assignment like $i += 2.
Exercise Print from 1 to 5
Use a for loop to print the numbers from 1 to 5, one per line, with echo.
Show example solution
Build the loop with for ($i = 1; $i <= 5; $i++) and print echo $i . "\n".
Example solution:
<?php
// Numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo $i . "\n";
}
Test yourself
-
What is the output of the loop below?
for ($i = 1; $i <= 3; $i++) { echo $i; }- 123
- 321
- 111
- 1234
Show answer
123 — Correct. $i becomes 1, 2 and 3 in turn, so 123 is printed.
-
Write the start of the countdown loop
for (____; $i >= 1; $i--) { echo $i; }Show answer
for ($i = 5; $i >= 1; $i--) { echo $i; } -
Match each for part to its meaning
- $i = 1
- Starting value
- $i <= 5
- Condition
- $i++
- Increment
-
How many times does for ($i = 10; $i >= 1; $i--) run?
for ($i = 10; $i >= 1; $i--) { echo $i; }- 9
- 11
- 10
- Infinite
Show answer
10 — Correct. There are 10 steps from 10 down to 1.