continue
suggest changeThe continue keyword halts the current iteration of a loop but does not terminate the loop.
Like the break statement, the continue statement sits inside the loop body. When it runs, the current iteration stops. In a while or do-while loop, execution continues at the condition. In a for loop, the increment runs first, then the condition. In foreach, iteration advances to the next element.
In the following example, the loop prints a message for each value 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 rest of the inner loop).