How to terminate or break a loop in PHP?

Use the break keyword inside a loop to stop it immediately. The code after the loop continues to run. It works in for, while, do...while, foreach and switch.

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 4) {
        break;      // stop the loop
    }
    echo $i . " ";
}
echo "<br>Loop ended";
?>

Output:

Tutorials Class - Output Window

1 2 3
Loop ended

In nested loops, break 2 stops two levels of loops at once. If you only want to skip one round and go to the next one, use continue. Both are explained in PHP Loops.


Learn more about the similar topics:
Tutorials
PHP Loops
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?