The for Loop in PHP
The for loop allows you to execute a block of
code a specified number of times.
The syntax is as follows: first, the initial value is specified, then the loop termination condition - as long as it is true, the loop continues to run, and then the post-iteration commands are specified.
Example
Let's use for as an example
to display a string of numbers from 1
to 9. To do this, the loop must iterate
9 times.
See the example solution below, followed by the breakdown:
<?php
for ($i = 1; $i <= 9; $i++) {
echo $i;
}
?>
Code execution result:
123456789
Example Breakdown
To solve the problem, a counter variable is introduced,
most often called $i.
This variable is assigned an initial value,
in our case 1.
Then the loop termination condition is set,
in our case, it's the condition $i <= 9.
It means that the loop runs as long as $i
is less than or equal to 9.
Then the post-iteration commands are set,
in our case - $i++. This means
that after each loop iteration we will increase
the variable $i by 1.
See Also
-
lesson
The foreach Loop in PHP -
lesson
The while Loop in PHP -
lesson
The for Loop in PHP