Breaking Out of Loops in PHP: Techniques and Best Practices
☰Fullscreen
Table of Content:
You can completely break out of a loop when it is still running. This is achieved with the break keyword. Once a loop is exited, the first statement right after it will be executed. The break keyword provides an easy way to exit a loop if an error occurs, or if you found what you were looking for.
Example:
"; if($a == 5){ break; } } print "
You have exited the loop."; ?>
In the above example, the for loop is set to iterate 9 times and print the current value of the variable a during each iteration. The if statement within the loop states that when the variable a is equal to 5, break out of the loop.
Output:
This will produce the following result
0 1 2 3 4 5 You have exited the loop.