➤ The for loop is used when you know in advance how many times the script should run.
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
➤ Parameters (divided by ; ):
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
For instance:
// outputs the numbers from 1 to 10
for ($i = 0; $i <= 10; $i++) {
echo "The number is: $i \n";
}
// Without first parameter
$i = 0;
for (; $i <= 10; $i++) {
echo "The number is: $i \n";
} // outputs the numbers from 1 to 10
// Without first and third parameter
$i = 0;
for (; $i <= 10;) {
echo "The number is: $i \n";
$i++; // we got the while loop syntax :))
} // outputs the numbers from 1 to 10
// We can make a for loop infinite without using these three parameters
for ( ; ; ){
echo "infinite \n";
}