For Loop in PHP
The for
loop allows you to repeat
some code a specified number of times.
Here is its syntax:
Here is its syntax:
<?php
for ( initial commands; end condition; commands after each iteration ) {
loop body
}
?>
Initial commands - this is what will be executed before the loop starts. They are executed only once. Usually, initial counter values are placed there. End condition - this is the condition under which the loop will run while it is true. Commands after each iteration - these are commands that will be executed every time at the end of a loop iteration. Usually, counters are incremented there.
Let's use the for
loop to display
numbers from 1
to 9
sequentially:
<?php
for ($i = 1; $i <= 9; $i++) {
echo $i;
}
?>
Now let's increment the counter not
by 1
, but by 2
:
<?php
for ($i = 1; $i <= 9; $i += 2) {
echo $i;
}
?>
You can perform a countdown:
<?php
for ($i = 10; $i > 0; $i--) {
echo $i;
}
?>
Use the for
loop to display
numbers from 1
to 100
.
Use the for
loop to display
numbers from 11
to 33
.
Use the for
loop to display
even numbers in the range from 0
to
100
.
Use the for
loop to display
odd numbers in the range from 1
to
99
.
Use the for
loop to display
numbers from 100
to 0
.