Breaking out of a loop in PHP

Rumman Ansari   Software Engineer   2020-02-05   5435 Share
☰ Table of Contents

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:



<?php
for($a = 0; $a < 10; $a++){
print $a . "<br />";
if($a == 5){
break;
}

}
print "<br />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.