+ 2

Return in a loop

Can someone tell me why the result bellow should be 10 and not 0, 1, 2, 3, 4. Thanks. My process is. I take 5, plug it in the loop and get 0, 1, 2, 3, 4. Then I add 0 to these results which still gives me 0, 1, 2, 3, 4. function func($arg) { $result = 0; for($i=0; $i<$arg; $i++) { $result = $result + $i; } return $result; } echo func(5);

1st Jul 2017, 12:53 AM
Alexis
Alexis - avatar
4 Answers
+ 11
$result = $result + Si; 0 + 1, $result becomes 1 1 + 2, $result becomes 3 3 + 3, $result becomes 6 6 + 4, $result becomes 10. Function returns value after loop has ended, and returns 10.
1st Jul 2017, 12:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Ok, that explains why the $result = 0 is written outside the loop. I didn't understand that. Thanks.
1st Jul 2017, 1:02 AM
Alexis
Alexis - avatar
+ 3
@Alexis Yes, you want to ensure you're not resetting to zero, and: $result is there is because you can't add to $result without defining it first. Remove the initializer (regardless of its value) and this happens: Notice: Undefined variable: result because: $result = undefined_variable + $i;
1st Jul 2017, 1:57 AM
Kirk Schafer
Kirk Schafer - avatar
0
Function returns value after loop has ended, and returns 10.
23rd Jul 2017, 8:44 PM
Mubarak Haruna
Mubarak Haruna - avatar