Loop and Return in PHP
Let's say we have a function that returns the sum
of numbers from 1
to 5
:
<?php
function func() {
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum += $i;
}
return $sum;
}
$res = func();
echo $res; // outputs 15
?>
Now let's place the return
inside the loop, like this:
<?php
function func() {
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum += $i;
return $sum;
}
}
$res = func();
echo $res;
?>
In this case, the loop will run for only one
iteration and an automatic exit from the function
(and consequently from the loop) will occur. And in one
iteration of the loop, the variable $sum
will contain
only the number 1
, not the entire required sum.
What will be output to the screen as a result of executing the following code:
<?php
function func($num) {
$sum = 0;
for ($i = 1; $i <= $num; $i++) {
$sum += $i;
return $sum;
}
}
echo func(5);
?>
Explain why.
What did the author of this code intend to do? Correct the author's mistake.