The for Construct
The for
construct is used to organize loops with a known number of iterations. It consists of three parts: counter initialization, loop continuation condition, and counter modification on each iteration.
Syntax
for (initialization; condition; increment) {
// code to be executed
}
Example
Let's output numbers from 0
to 4
:
<?php
for ($i = 0; $i < 5; $i++) {
echo $i . ' ';
}
?>
Code execution result:
0 1 2 3 4
Example
Let's iterate through array elements:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
for ($i = 0; $i < count($arr); $i++) {
echo $arr[$i] . ' ';
}
?>
Code execution result:
a b c d e
Example
Let's output numbers from 10
to 1
in reverse order:
<?php
for ($i = 10; $i >= 1; $i--) {
echo $i . ' ';
}
?>
Code execution result:
10 9 8 7 6 5 4 3 2 1