In PHP, the break
and continue
statements are used within loops to alter the flow of execution. Here’s an explanation of how break
and continue
work in PHP:
break
statement:
Thebreak
statement is used to exit a loop prematurely. When encountered, thebreak
statement terminates the execution of the innermost loop (whether it’s afor
,while
,do-while
, orforeach
loop) and continues execution with the next statement after the loop.
Example of using break
:
for ($i = 0; $i < 5; $i++) {
if ($i == 3) {
break; // Exit the loop when $i equals 3
}
echo $i . ' ';
}
PHP
Output:
0 1 2
PHP
In this example, the loop iterates from 0 to 4. When $i
is equal to 3, the break
statement is encountered, and the loop is immediately terminated. The value of $i
is never echoed when it’s 3.
continue
statement:
Thecontinue
statement is used to skip the current iteration of a loop and move to the next iteration. When encountered, thecontinue
statement jumps to the next iteration, without executing the remaining code within the loop for that particular iteration.
Example of using continue
:
for ($i = 0; $i < 5; $i++) {
if ($i == 2) {
continue; // Skip the current iteration when $i equals 2
}
echo $i . ' ';
}
PHP
Output:
0 1 3 4
PHP
In this example, the loop iterates from 0 to 4. When $i
is equal to 2, the continue
statement is encountered. As a result, the code within the loop for that iteration is skipped, and the loop proceeds to the next iteration.
Both break
and continue
statements provide control over the execution flow within loops, allowing you to selectively exit the loop or skip specific iterations based on certain conditions.