PHP loop Condition
PHP loop Condition
PHP loop Condition, it can be used to traverse the set of code for the specified number of times and The loopfor is used when you know in advance that how many times the script should run. It should be used if a number of iteration is known otherwise used while loop Condition.

Syntax
|
1 2 3 |
for(initialization; condition; increment/decrement){ //code to be executed here } |
PHP loop Condition: Flowchart

Example-
|
1 2 3 4 5 |
<?php for($n=11;$n<=20;$n++){ echo "$n<br/>"; } ?> |
|
1 2 3 4 5 6 7 8 9 10 |
11 12 13 14 15 16 17 18 19 20 |
PHP Nested For Loop
For loop Condition and loop Condition in PHP Programming, We can also use for loop inside for loop in PHP, it is called as nested for loop.
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
Example-
|
1 2 3 4 5 6 7 |
<?php for($i=1;$i<=3;$i++){ for($j=1;$j<=3;$j++){ echo "$i $j<br/>"; } } ?> |
Output-
|
1 2 3 4 5 6 7 8 9 |
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 |
PHP For Each Loop-
The loopfor each works only on arrays and is used to loop through each key/value pair in an array or PHP for each loop is used to traverse array elements.
Syntax-
|
1 2 3 |
foreach ($array as $value) { code to be executed; } |
The following example demonstrates a loop that will output the values of the given array ($colors):
Example-
|
1 2 3 4 5 6 7 |
<?php $colors = array("White", "Red", "blue", "Pink"); foreach ($colors as $value) { echo "$value <br>"; } ?> |
Finally Output-
|
1 2 3 4 |
White Red Blue Pink |
Resource
PHP