loops in php | php tutorial | learn php

Sometimes, within our code, we need to execute a set of statements multiple times which may or may not be based on particular condition. So rather writing a same code lines multiple times, we can use loops in php.

Loops in php are used to execute a set of statements multiple times as long as the provided condition evaluates to true.

For example, if you want to crawl through different values within an array, you can use foreach loop in php.

There are mainly four types of loop in php

– for loop

– while loop

– do…..while loop

– foreach loop

for loop in php

for loop in php is used to execute a set of statement, number of times based on a numerical value.

This loop is generally used when we know in advance how many times a statement needs to be executed.

Syntax of for loop

In for loop a counter variable is used to track the number of iterations and also use to check the condition to terminate the loop.

For loop in php consist of three blocks –

– initialize counter: sets and initialize the counter variable
– test condition: this is the condition which is checked for each iteration, only when the condition evaluates to TRUE, the loop is executed, otherwise it’ll get terminated.

– update counter: this block is used to update the counter variable value with each iteration.  


In the above example we’ve used $i as our counter variable. We initialized it to 1 and checked it weather $i is less than or equal to 1 or not, in last we’re updating it by 1 with each iteration.

When the value of $i becomes greater than 10, the condition will become FALSE and the loop will terminate.


1 2 3 4 5 6 7 8 9 10

Also Check – while loop in php

Author: Deepak Kumar

This is Deepak Kumar, founder of True Infosystems and of-course the chief content creator at CodingLessions.info. Started my carrier as a Freelancer and now a top-rated Freelancer at Upwork, delivered over 200 successful projects with highly positive user ratings and counting.