0

Module 6 Quiz: 1 st question

It is about RETURN function: What output results from the following code? function func($arg) { $result = 0; for($i=0; $i<$arg; $i++) { $result = $result + $i; } return $result; } echo func(5); Why the answer is 10 instead of 15?Kind of messed up Return and Echo

31st Oct 2017, 8:05 PM
Feiling
Feiling - avatar
4 Answers
+ 4
$i<$arg this expression stops the loop when $i is equal to 5 so the body of the loop isn't ran and the last value of $i (5) isn't added to the variable $result. 0 + 1 + 2 + 3 + 4 = 10
31st Oct 2017, 8:13 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
As I read your final sentence, a return statement is used to return a value (a processed data) from a function to another code that calls the function (function caller), while echo does not return the value, instead, it outputs its arguments directly to the screen (browser window).
1st Nov 2017, 8:33 AM
Ipang
0
What the for loop does is keep summing up numbers until the limit is reached. So starting from 0, $result = 0+1+2+3+4 = 10 finally, return $result. Hope this helped.
31st Oct 2017, 8:15 PM
Witty Phantom
Witty Phantom - avatar
0
answer is ~ .
14th Jan 2020, 12:55 PM
Imanuel Wicaksono
Imanuel Wicaksono - avatar