The Break Statement in PHP
Let's say we have a loop that outputs array elements to the screen:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
}
?>
Suppose our task is to determine
if the array contains the number 3
. If it does,
- we will output '+++'
to the screen (and
if it doesn't - we will do nothing).
Let's solve our task:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
if ($elem == 3) {
echo '+++';
}
}
?>
The task is solved, however, there is a problem: after
the number 3
has been found, the array
still continues to be pointlessly iterated
further, wasting valuable CPU resources and
slowing down our script.
It would be more optimal to terminate
our loop immediately after finding the
number. This
can be done using a special
break
statement, which allows for premature termination
of the loop.
So, let's terminate the loop as soon as we
encounter the number 3
:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
if ($elem == 3) {
echo '+++';
break; // exit the loop
}
}
?>
The break
statement can terminate any loops:
foreach
, for
, while
.
Given an array with numbers. Start a loop that
will output the elements of this
array to the console one by one until an
element with the value 0
is encountered.
After that, the loop should terminate.
Given an array with numbers. Find the sum of the elements from the beginning of the array to the first negative number.
Given an array with numbers. Find the position of the first
number 3
in this array (assuming that
this number is definitely in the array).
Determine how many integers, starting
from the number 1
, need to be added so that the sum
becomes greater than 100
.