Continue and Break statements are used within loops (like for, foreach, while, and do-while) to control the flow of execution.
Continue Statement:
- Purpose: Skips current iteration in a loop.
- Effect: When encountered, it skips the rest of the code in the current loop iteration and jumps to the next iteration.
Break Statement:
- Purpose: Immediately exits the loop
- Effect: When encountered, it stops the loop completely, even if there are more iterations remaining. The script continues execution after the loop..
Here's a basic example illustrating the difference between continue and break:
<?php
// Example illustrating continue and break
echo "Using continue:\n";
for ($i = 1; $i <= 5; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . "\n"; // Print only odd numbers
}
echo "\nUsing break:\n";
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break; // Exit loop when i equals 3
}
echo $i . "\n"; // Print numbers until i equals 3
}
?>
Output:
Using continue:
1
3
5
Using break:
1
2
In this example:
- With continue, the loop continues to the next iteration after skipping even numbers.
- With break, the loop stops completely when i equals 3, even though there are more iterations remaining.