The
continue
keyword halts the current iteration of a loop but does not terminate the loop.
Just like the break
statement the continue
statement is situated inside the loop body. When executed, the continue
statement causes execution to immediately jump to the loop conditional.
In the following example loop prints out a message based on the values in an array, but skips a specified value.
$list = ['apple', 'banana', 'cherry'];
foreach ($list as $value) {
if ($value == 'banana') {
continue;
}
echo "I love to eat {$value} pie.".PHP_EOL;
}
The expected output is:
I love to eat apple pie.
I love to eat cherry pie.
The continue
statement may also be used to immediately continue execution to an outer level of a loop by specifying the number of loop levels to jump. For example, consider data such as
Fruit | Color | Cost |
---|---|---|
Apple | Red | 1 |
Banana | Yellow | 7 |
Cherry | Red | 2 |
Grape | Green | 4 |
In order to only make pies from fruit which cost less than 5
$data = [
[ "Fruit" => "Apple", "Color" => "Red", "Cost" => 1 ],
[ "Fruit" => "Banana", "Color" => "Yellow", "Cost" => 7 ],
[ "Fruit" => "Cherry", "Color" => "Red", "Cost" => 2 ],
[ "Fruit" => "Grape", "Color" => "Green", "Cost" => 4 ]
];
foreach($data as $fruit) {
foreach($fruit as $key => $value) {
if ($key == "Cost" && $value >= 5) {
continue 2;
}
/* make a pie */
}
}
When the continue 2
statement is executed, execution immediately jumps back to $data as $fruit
continuing the outer loop and skipping all other code (including the conditional in the inner loop.