The Continue Statement in PHP
In addition to the break statement, which terminates
a loop, there is also the continue statement, which starts a new iteration
of the loop. This statement can sometimes be
useful for simplifying code, although almost
any task can be solved without it. Let's
look at a practical example.
Suppose we are given an array with numbers. Let's
loop through it and square the numbers divisible by
2, then output them
to the screen, and cube the numbers divisible by 3,
then output them to the screen.
Here is the solution to the described task:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $elem) {
if ($elem % 2 === 0) {
$res = $elem * $elem;
echo $res;
} elseif ($elem % 3 === 0) {
$res = $elem * $elem * $elem;
echo $res;
}
}
?>
As you can see, the line echo $res
is repeated twice. Let's move it
out of the if, like this:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $elem) {
if ($elem % 2 === 0) {
$res = $elem * $elem;
} elseif ($elem % 3 === 0) {
$res = $elem * $elem * $elem;
}
echo $res; // moved output out of the condition
}
?>
Now, however, our script works a bit
differently: it turns out that for regular elements,
not processed by our if, the
output of the variable $res
will also be executed, which according to the conditions of our task we
do not need.
Let's fix the problem by adding an else
condition to our if, which will trigger
for elements not divisible by 2 and
3, and call the continue statement there,
which will immediately throw us
to the next iteration of the loop:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $elem) {
if ($elem % 2 === 0) {
$res = $elem * $elem;
} elseif ($elem % 3 === 0) {
$res = $elem * $elem * $elem;
} else {
continue; // move to the next loop iteration
}
echo $res; // will execute if divisible by 2 or 3
}
?>
Write a loop that outputs only
even numbers from 1 to 100,
skipping odd numbers using continue.