PHP For Loop, Nested For Loop Iteration with Examples

In this tutorial, learn how to use the PHP for loop and nested loop to perform iteration. The loop is useful to test certain condition and execute the code when the condition is true. It is useful to create real applications using PHP.

What is For Loop in PHP?

A for loop in PHP is used to iterate through a block of code for the specified number of times. You can use this loop when you know about how many times you want to execute the block of code.


Description of parameters
You have to use the above syntax according to the description given below.

Sr No Parameter Name Description
1 Initialization You have to initialize the loop counter variable.
2 test condition A test condition is evaluated before the loop performs iteration. If the condition is TRUE, it executes the block of codes and the loop continues. If the given condition is FALSE, the loop stops performing iteration.
3 increment/decrement Use this parameter to define the counter as an increase or decrease as per the required number of iteration.

The loop executes the block of codes as long as the certain condition is true. If you don’t know the number iteration to perform over a block of code, you should use the PHP while loop.

How to Use it to Perform Iteration

To use for loop in PHP, you have to follow the above-given syntax. The below example shows the use of the for loop in PHP. The loop first initializes the variable $x from 0. It performs the iteration and executed the block of code until the variable $x is less than 9.



The above example shows the numbers from 0 to 9. The third parameter of the loop increment the counter from 1 each time the loop perform the iteration.

Its the single for loop operation to perform the iteration. However, you also use the for loop inside another loop. Keep reading this post to learn the nested loop method in the next section.

Nested For Loop in PHP

The nested loop is the method of using the for loop inside the another for loop. It first performs a single iteration for the parent for loop and executes all the iterations of the inner loop. After that, it again checks the parent iteration and again performs all the iteration of the inner loop.

The same process continuously executed until the parent test condition is TRUE.





The above example showing the star patterns using the nested for loop. It performs the parent iteration for 3 times and for every single iteration of the parent for loop, it executed the inner iteration for full 3 times.

Hope, you like this post of how to use PHP for loop and nested loop. If you have any query regarding the tutorial, please comment below.

Also tell me, which method you are using with PHP for loop by comment below.