PHP Loops are used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. PHP is supports four different types of loops.

for loops - This type of loops is used through a block of code a specified number of times.

while loops − The while loop is also an entry control loop like for loops this loop through a block of code as long as the specified condition is true.

do while loops − This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition.

foreach loops − works only on arrays and it's through each key/value pair in an array.

PHP for Loop

This type of loops is used through a block of code a specified number of times.

Syntax :

for(initialization; condition; increment){
     Code to be executed
}

Example :

<?php
for($i=1; $i<=10; $i++){
    echo "The number is " . $i . "<br>";
}
?>

PHP while Loop

The while loop is also an entry control loop like for loops this loop through a block of code as long as the specified condition is true.

Syntax :

while (condition is true) {
  code to be executed;
}

Example :

<?php
$x = 1;

while($x <= 10) {
  echo "The number is: $x <br>";
  $x++;
}
?>

PHP do while Loop

This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition.

Syntax :

do {
   code to be executed;
}
while (condition);

Example :

<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>

PHP foreach Loop

The foreach loop works only on arrays and it's through each key/value pair in an array.

Syntax :

foreach($array as $value){
    // Code to be executed
}

Example :

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>