A for loop is made up of a declaration, a condition, and an action:
The general syntax of a for loop is as follows:
for ( declaration; condition; action ) {
// Run this code
}
// More code here
Here is how a for loop looks in PHP:
<?php
for ($i = 1; $i < 10; $i++) {
print "Number $i\n";
}
?>
The code above generates the following result.
As you can see, the for loop has the three parts separated by semicolons. In the declaration, we set the variable $i to 1.
For the condition, we have the loop execute if $i is less than 10.
Finally, for the action, we add 1 to the value of $i for every loop iteration.
The following example has an infinite loop.
<?php for (;;) { print "In loop!\n"; } ?>
You can nest loops as you see fit, like this:
<?php
for ($i = 1; $i < 3; $i = $i + 1) {
for ($j = 1; $j < 3; $j = $j + 1) {
for ($k = 1; $k < 3; $k = $k + 1) {
print "I: $i, J: $j, K: $k\n";
}
}
}
?>
The code above generates the following result.