PHP Loops | for

Hi everyone,

The for loop is used when you know in advance how many times the script should run. The syntax is:

for (init; condition; increment)
{
// code to be executed;
}
  • init: We use this mostly to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: We use this mostly to increment a counter (but can be any code to be executed at the end of the iteration)

Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas).

Here goes an example:

output will be :

Here are the numbers from 1 to 10 
1
2
3
4
5
6
7
8
9
10

<?php
echo "Here are the numbers from 1 to 10 </br>";
for ($i = 0; $i < 10; $i++) {
    echo $i + 1 . "</br>";
}
?>

The very first value of $i is 0 and for the first time the loop is executed we see its value incremented by 1. This repeats 10 times so we can see the numbers from 1 to 10 in each line.

Now, you have learned the for loop in PHP. Stay cool and stay connected! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *