PHP Loops

A loop runs the same block of code again and again, while a condition is true. It saves you from writing the same line many times. PHP has four loops: for, while, do...while and foreach.


for loop

Use for when you know how many times to repeat. It has three parts: a start value, a condition, and a step.

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

Output:

Tutorials Class - Output Window

1 2 3 4 5

while loop

The while loop checks the condition first and runs while it is true. Be careful to change the value inside the loop, or it will never stop.

<?php
$i = 1;
$sum = 0;

while ($i <= 5) {
    $sum += $i;
    $i++;
}

echo "Sum = " . $sum;
?>

Output:

Tutorials Class - Output Window

Sum = 15

do…while loop

The do...while loop runs the code at least one time, and then checks the condition.

<?php
$i = 10;

do {
    echo $i;
    $i++;
} while ($i < 5);
?>

Output:

Tutorials Class - Output Window

10

foreach loop

Use foreach to go through all the values of an array. It is the easiest loop for arrays.

<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

$user = ["name" => "Robin", "city" => "Delhi"];

foreach ($user as $key => $value) {
    echo $key . " = " . $value . "<br>";
}
?>

Output:

Tutorials Class - Output Window

Apple
Banana
Cherry
name = Robin
city = Delhi


break and continue

  • break stops the loop completely.
  • continue skips the rest of the current round and goes to the next one.
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 3) {
        continue;   // skip 3
    }
    if ($i == 6) {
        break;      // stop at 6
    }
    echo $i . " ";
}
?>

Output:

Tutorials Class - Output Window

1 2 4 5


Nested loops

A loop inside another loop is a nested loop. For every round of the outer loop, the inner loop runs fully.

<?php
for ($row = 1; $row <= 3; $row++) {
    for ($col = 1; $col <= 3; $col++) {
        echo $row * $col . " ";
    }
    echo "<br>";
}
?>

Output:

Tutorials Class - Output Window

1 2 3
2 4 6
3 6 9

Note: Which loop to use? for when the count is known, while when it depends on a condition, and foreach for arrays. See also how to stop a script.

Next chapter: PHP Functions.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a program to count 5 to 15 using PHP loop
Write a factorial program using for loop in php
Write a program to create Chess board in PHP using for loop
Write a Program to create given pattern with * using for loop
Write a PHP script to displays numbers between 100 and 150 divisible by 4
Interview Questions & Answers
How to terminate or break a loop in PHP?