Using Return in a Loop in PHP
The fact that return
is located inside a loop
is not always a mistake.
The following example shows a function that
determines how many of the first elements of an array
need to be added so that the sum becomes greater than or
equal to 10
:
<?php
function func($arr) {
$length = count($arr);
$sum = 0;
for ($i = 0; $i < $length; $i++) {
$sum += $arr[$i];
// If the sum is greater than or equal to 10:
if ($sum >= 10) {
return $i + 1; // exit the loop and the function
}
}
}
$res = func([1, 2, 3, 4, 5]);
echo $res;
?>
The following example shows a function that
calculates how many integers, starting from
1
, need to be added so that the result
is greater than 100
:
<?php
function func() {
$sum = 0;
$i = 1;
while (true) { // infinite loop
$sum += $i;
if ($sum >= 100) {
return $i; // the loop runs until it exits here
}
$i++;
}
}
echo func();
?>
Write a function that will take a number as a parameter
and divide it by 2
as many times as needed until the result becomes less than
10
. Let the function return the number of
iterations that were required to achieve the
result.