When working with loops (for, foreach, while, and do-while), the code normally runs sequentially from start to finish for every item or iteration.
However, you often need to alter this default flow—either to stop a loop early because you found what you were looking for, or to skip the rest of the current loop lap and jump immediately to the next one.
In PHP, we control this execution flow using the break and continue keywords.
The break statement instantly terminates the execution of the loop it is inside.
The program completely abandons the loop and continues running any code written immediately below the loop structure.
Use break when continuing the loop is unnecessary or inefficient (e.g., searching a collection for a single item and stopping once it is found).
Example with foreach
<?php
$userIDs = [101, 102, 103, 104, 105];
$searchFor = 103;
foreach ($userIDs as $id) {
if ($id == $searchFor) {
echo "Found ID: " . $id . ". Stopping search.";
break; // Exits the foreach loop completely
}
echo "Checking ID: " . $id . "\n";
}
echo "Loop is over. Moving on.";
// Output:
// Checking ID: 101
// Checking ID: 102
// Found ID: 103. Stopping search.
// Loop is over. Moving on.
The continue statement stops the execution of the current iteration (the current lap) of the loop.
Instead of exiting the loop entirely, it immediately jumps back to the top of the loop structure to evaluate the condition and start the next lap.
Use continue to skip over specific invalid, empty, or restricted items while still allowing the rest of the items to be processed normally.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips the rest of this block and jumps straight to $i++
}
echo "Processing number: " . $i . "\n";
}
// Output:
// Processing number: 1
// Processing number: 2
// Processing number: 4
// Processing number: 5
// (Notice how the number 3 is missing from the output because continue skipped the echo statement for that iteration).
break - exits entirely: It acts as an emergency stop button that throws you out of the loop completely.
continue - skips a lap: It resets the loop back to the top to start the next iteration, skipping any code written directly underneath it.
Semicolon required: Both break; and continue; are individual language statements and must be followed by a semicolon.