Breaking Out of Loops in PHP: Techniques and Best Practices

Rumman Ansari   Software Engineer   2024-07-18 09:21:06   5424  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰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:



<?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.


MCQ Available

There are 4 MCQs available for this topic.

4 MCQ