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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.