PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.

In php their are 4 major loops that mostly used. Those are “foreach, while, do while, for” loops.

Foreach loop

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects. There are two syntaxes for foreach loop:

1.1 foreach (expression as $value)


1.2 foreach (expression as $key => $value)

For more detailed explanation here is a video

While loop

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.

do-while loop

very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. 

For loop

for loops are the most complex loops in PHP. The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.