Loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times.
For Loop in PHP
For loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.
Syntax = for (initialization expression; test condition; update expression)
{
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
- initilization epresssion= in this expression we have to initialize the loop counter to some value. for example: $num = 1;
- test epression=in this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;
- update expression= after executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;
Flow Diagram:
Example of FOR LOOP
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
Ouptut
1
2
3
4
5
6
7
8
9
10