break and continue
Learn to end a loop with break and skip a step with continue.
The break command
Sometimes you want to stop a loop before its condition ends it. The break command exits the loop at once and moves to the code after it. It is handy when you find the value you were looking for.
For example, when searching a list for a target number, if ($item == $target) { break; } stops the loop as soon as the target is found, so no extra work is done.
The continue command
The continue command skips the current step and jumps to the next one. It does not leave the loop, it only ends that turn. It is useful for skipping elements that meet a certain condition.
For example, to skip even numbers from 1 to 5 you write if ($i % 2 == 0) { continue; }. The loop skips the turn on even numbers and only the odd numbers get printed.
Exercise Print the odd numbers
Loop through the numbers from 1 to 9 with a for loop. Skip even numbers with continue; print only the odd numbers, one per line, with echo.
Show example solution
Write for ($i = 1; $i <= 9; $i++), skip evens with if ($i % 2 == 0) { continue; }, then echo $i . "\n".
Example solution:
<?php
// Odd numbers from 1 to 9
for ($i = 1; $i <= 9; $i++) {
if ($i % 2 == 0) {
continue;
}
echo $i . "\n";
}
Test yourself
-
What does the break command do in a loop?
- It ends the loop completely
- It skips one step
- It resets the counter
- It throws an error
Show answer
It ends the loop completely — Correct. break exits the loop completely.
-
Stop the search loop
$found = false; foreach ($items as $item) { if ($item == $target) { $found = true; ____; } }Show answer
$found = false; foreach ($items as $item) { if ($item == $target) { $found = true; break; } } -
Match each command to its behavior
- break
- Ends the loop completely
- continue
- Skips one step, continues
- $i++
- Increases counter by one
-
What does the continue command do in a loop?
- It ends the loop
- It decreases the counter
- It skips that step and keeps looping
- It deletes all variables
Show answer
It skips that step and keeps looping — Correct. continue skips that step and the loop moves to the next one.