The for loop is utilized when you know the exact number of times the script should execute.
for (expression1, expression2, expression3) { |
Here’s how it works:
Output the numbers from 0 to 10:
for |
$x = 0;
, is evaluated once to initialize the counter at 0.$x <= 10;
, is checked before each iteration, and the code block runs only if this condition is true. In this case, the condition remains true as long as $x is less than or equal to 10.$x++;
, is evaluated after each iteration, increasing the value of by one with each cycle.Using the break statement, we can exit the loop even if the condition remains true.
Exit the loop when $x reaches 3:
for |
The continue statement allows us to skip the current iteration and move on to the next one.
Skip to the next iteration if $x is 3:
for |
This example counts to 100 in increments of ten:
for ($x = 0; $x <= 100; $x+=10) { echo “The number is: $x <br>”;} |