In this tutorial, you will learn how to use for loop in PHP to execute a block of code repeatedly.
PHP For Loop executes a block of code repeatedly until a certain condition is true. This is typically used to execute a block of codes a certain number of times.
That means for
loop is used when you already know how many times the block of code needs to be executed. If you not sure about the number of iteration, you should use the while
loop.
PHP For Loop Syntax
for(initialization; condition; increment/decrement){ //code to be executed }
The parameters of For Loop are explained below.
initialization – This is the first parameter of for loop. It is used to initialize the loop counter variable and evaluates once unconditionally before entering into the actual loop.
condition – It evaluates at each iteration of the loop. If the condition is true, the loop continues and executes the nested block. If the condition evaluates false, then the loop ends.
increment/ decrement – It updates the loop counter value at the end of each iteration.
Example
<?php for($i=1;$i<=5;$i++){ echo "$i<br/>"; } ?>
Output
2
3
4
5
Example
All the three parameters in for loop are optional. But you must have to pass the semicolon(;) in order to avoid syntax error.
<?php $a = 1; //This will be a infinite loop for (;;) { echo $a++; echo "</br>"; } ?>
Output
2
3
.
.
.
PHP Nested For Loop
If one for loop inside another for loop is called nested for loop. The inner loop executes only when the outer loop’s condition is true.
In case of inner or nested for loop, inner for loop is executed completely for one outer for loop. If outer for loop is to be executed for 2 times then inner for loop will be executed tota 4 times (2 times for 1st outer loo and, 2 times for 2nd outer loop).
Example
<?php for($x=1;$x<=2;$x++){ for($y=1;$y<=2;$y++){ echo "$x $y<br/>"; } } ?>
Output
1 2
2 1
2 2