Loops in PHP or any other programming language are used to perform repeated operation or execute same block of code for specified number of times. There are four most commonly used PHP Loops.

For

For Loop executes the code block specified number of times, and consist of four parts initial seed, test condition, increment/decrement and code block to execute. Following example will print number 1 to 5 using For loop.

<?php 
for ($counter = 1; $ counter <= 5; $counter++) {
    echo "$counter";
} 
?>	

While

While Loop is another way to execute repeated code in PHP, it checks the condition and executes code block as long as condition remains true. Following example is prints numbers 1 to 5 using While loop.

<?php 
$counter = 1;
while($counter <= 5) {
    echo "$counter";
    $counter++;
} 
?>

Do-While

Do-While Loop is another form of looping mechanism which repeatedly executes the code but one key difference from earlier while loop is, it executes code block first time regardless condition is true or false, and starts next iteration if condition is true or remains true. The above example can be re-written as Do-While loop to print number from 1 to 5.

<?php 
$counter = 0;
do {
    echo "$counter";
    $counter++;
} while ($counter <= 5);
?>

Foreach

Foreach loop is another common way to executing repeating code, this is similar to For loop, but it iterates over collection and executes for each item in array or collection. Unlike For loop it doesn’t have any condition or increment/decrement values.

<?php 
$numbers = array("1", "2", "3", "4", "5");
foreach ($numbers as $num) {
    echo "$num";
}
?>