Welcome back! You've already learned about while
, do-while
, for
, and foreach
loops. Now you're ready to take your understanding of loops to the next level. In this lesson, we'll explore how to control the flow of your loops using two important keywords: break
and continue
.
In this lesson, you'll discover how to use the break
and continue
statements within your loops:
break
: This keyword immediately stops the execution of the loop when a certain condition is met.continue
: This keyword skips the current iteration and proceeds to the next iteration of the loop.
Let's take a look at an example to illustrate these concepts:
php1<?php 2for ($sector = 1; $sector <= 10; $sector++) { 3 if ($sector == 5) { 4 echo "Critical issue in sector " . $sector . ", stopping mission!\n"; 5 break; // Stop the mission at sector 5 6 } 7 if ($sector == 2) { 8 echo "Skipping sector " . $sector . "\n"; 9 continue; // Skip sector 2 10 } 11 echo "Scanning sector " . $sector . "\n"; 12} 13?>
In this code, we use break
to stop the loop entirely when we reach sector 5, and continue
to skip over sector 2.
Output:
1Scanning sector 1 2Skipping sector 2 3Scanning sector 3 4Scanning sector 4 5Critical issue in sector 5, stopping mission!
Mastering the use of break
and continue
enhances your control over loop execution. This is crucial in scenarios where you need to:
- Terminate a loop early: For example, stopping a search as soon as the target is found.
- Skip specific iterations: For example, ignoring faulty data during batch processing.
Using these tools effectively makes your code more flexible and efficient. You'll be able to handle a variety of real-world conditions and exceptional cases within your loops.
Exciting, right? Let’s head to the practice section to get hands-on experience with break
and continue
in loops!