PHP For Loop is a loop statement which can be used in various forms to execute a block of code continuously as long as the condition of the loop is true, and stops only when the condition fails. These are:
For Loop :
For loop is used to execute a group of action only for a specified number of times.
Syntax:
for(initialization; condition; increment/decrement) { code to be executed till the condition is true; } |
For Each Loop :
For Each loop is used for traversing an array to execute a group of action for each elements in an array.
Syntax:
foreach ($array as $element) { code to be executed; } |
Nested For Loop :
Nested For loop is For loop inside a For loop and so on which is used to run multiple loop conditions.
Syntax:
for(initialization; condition; increment/decrement) { for(initialization; condition; increment/decrement) { code to be executed till the condition is true; } } |
Example 1: Example of For loop
<!DOCTYPE html> <html> <body> <?php for ($i = 0; $i <= 10; $i++) { echo "The number is: $i <br>"; } ?> </body> </html> |
Output
The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10 |
Example 2: Example of For Each loop
<!DOCTYPE html> <html> <body> <?php $colors = array("BMW", "Ford", "Hyundai", "Jaguar"); foreach ($colors as $value) { echo "$value <br>"; } ?> </body> </html> |
Output
BMW Ford Hyundai Jaguar |
Example 3: Example of Nested For loop
<!DOCTYPE html> <html> <body> <?php for ($i = 0; $i <= 2; $i++) { for ($j = 0; $j <= 5; $j++) { $sum = $i+ $j; echo "$sum<br>"; } echo "<br>"; } ?> </body> </html> |
Syntax:
0 1 2 3 4 5 1 2 3 4 5 6 2 3 4 5 6 7 |