Loops in PHP
Loops are by far the most powerful component of PHP. A loop is simply a set of statements repeated more than once.
There may be a situation when you need to execute a block of code several number of times. But when you are running the same code over and over would produce the same result. So what is the benefit of using Loop in that case? Basically a loop contains a variable that changes slightly each time.
The For Loop
PHP for loop can be used to traverse set of code for the specified number of times. For example if you want to repeat something ten or twenty times.
It should be used if number of iteration is known otherwise I recommend you to use while loop.
for (Initialization; Condition; Progressive)
//set of statements to be executed;
Initialization: Initialize the loop counter value
Condition: Check for condition. If it evaluates to TRUE, the loop continues. If FALSE then the loop ends.
Progressive: Increase / Decrease the loop counter value
for($var=1; $var<=20; $var=$var+1)
echo $var .” ”;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Example to display 1st 20 natural numbers in drop-down list
for($i=1; $i<=20; $i++)
echo “<option>”.$i. “</option>”;
Please note inside loop area we are using variable $i to display values in drop-down list as we use variable that changes slightly each time
The Nested For Loop: We can use for loop inside another for loop in PHP, it is known as nested for loop. In case of inner or nested loop, nested for loop is executed fully for one outer for loop.
Example, If outer loop is to be executed for 2 times and nested Inner loop for 2 times, then the nested inner loop will be executed 4 times (2 times for 1st outer loop and 2 times for 2nd outer loop).
for($i=1; $i<=5; $i++)
for($j=1; $j<=$i; $j++)
echo $j. ” “;
1 2 3
1 2 3 4
1 2 3 4 5