PHP Loops Interview Questions & Answers

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.