PHP Loop Control Structures
"Loop iteration" is one round of the loop (or one time that the group of code is executed).
In PHP, we have two loop control structures.
- Break - Ends the execution of the current loop.
- Continue - Skips the next part of current loop iteration, and jumps to condition checking of the next loop iteration.
Note: They can also be used with the switch statement.
PHP Break
break; statement terminates the execution of the current loop.
PHP Break Example
<?php
/*break on 5 */
$a = 0;
while ($a < 10) {
echo $a . '<br>';
if ($a === 5) {
break;
}
$a++;
}
Run Example ››An optional numeric argument can be used to specify how many loops need to be broken. (break 2; will terminate 2 nested loops)
PHP Break Example
<?php
for ($a = 0; $a < 10; $a++) {
echo "$";
for ($b = 0; $b < 10; $b++) {
if ($a === 3 && $b === 5) {
echo '<br> Breaking two loops';
break 2;
}
echo $b;
}
echo '<br>';
}
Run Example ››PHP Continue
continue; skips the next part of the current loop iteration. Then, the next loop iteration will run after checking the conditions.
Like break; statement, continue; also can have a numeric argument to continue multiple loops.
PHP Continue Example
<?php
$a = 0;
while ($a < 10) {
if ($a === 5) {
$a++;
continue; // 5 is not printed
}
echo $a . '<br>';
$a++;
}
Run Example ››
Visit PHP Help group to get some help from experts.