16. Breaking and Continuing Loops
Sometimes, you need to alter the standard flow of a loop based on a specific condition. PHP provides break and continue for this purpose.
The break Statement
break immediately terminates the execution of the current for, while, do-while, foreach, or switch structure.
Example: Stopping when a target is found.
php
<?php $items = [10, 25, 40, 50, 75]; $target = 40; foreach ($items as $item) { if ($item == $target) { echo "Found target: " . $target . "! Stopping search."; break; // Exit the loop entirely } echo "Checking item: " . $item . "<br>"; } ?>The continue Statement
continue stops the current iteration of the loop and moves immediately to the next iteration (re-evaluating the condition).
Example: Skipping unwanted values.
php
<?php for ($i = 1; $i <= 10; $i++) { // Skip iteration if $i is an even number if ($i % 2 == 0) { continue; } echo "Processing odd number: " . $i . "<br>"; } /* Output: Processing odd number: 1 Processing odd number: 3 ... */ ?>