+ 5

PHP

plz anyone can help me to understand this PHP code function func($arg) { $result = 0; for($i=0; $i<$arg; $i++) { $result = $result + $i; } return $result; } echo func(5);

10th Apr 2019, 3:05 PM
Ekram Mallick
Ekram Mallick - avatar
3 Answers
+ 1
The function 'func' receives an argument ($arg) I will refer to the $arg as N Creates an auxiliar variable ($result) The for statement Repeats N times: Add "i" to $result And finally returns the $result. Lets do it "func(5)": N=5 ($arg in reality) $result = 0 (Now we repeat N (5) times the content of the for statement) $result = $result (0) + $i (0) //result = 0 $result = $result (0) + $i (1) //result = 1 $result = $result (1) + $i (2) //result = 3 $result = $result (3) + $i (3) //result = 6 $result = $result (6) + $i (4) //result = 10 Finally returns 10 As we call "echo func(5)" and func returns 10 the result is "echo 10" and PHP shows 10 in the output Sorry for bad English and follow me if you understand 😁
10th Apr 2019, 3:41 PM
Nahuel Ourthe
Nahuel Ourthe - avatar
+ 2
The answer would be 10. Explanation: You have a variable called result initialized to 0. Then you have a loop which iterates from 0 to arg-1 (in this case 4). In each iteration it adds the current value of arg to result. So if I illustrated the iteration values and the corresponding value of it, it would be like this. 0: 0+0 = 0 1: 0+1 = 1 2: 1+2 = 3 3: 3+3 = 6 4: 6+4 = 10 So finally the answer is 10.
10th Apr 2019, 3:31 PM
Seniru
Seniru - avatar
+ 2
you have a function called func which takes 1 parameter as an argument called arg...the $ sign is php way of saying this is a variable...in the function there's a for loop which increments variable $i and stores it in $result + the previous $i-s till $i reaches the passed argument minus 1 because the condition of the for loop is $i less than $arg...than it returns the the variable $result...the code actually executes from the last line and than to the top because that's where the function is called...echo func(5) means print the result returned by the function func and you're passing it 5 as a parameter. So the result of this code should be 10 because 0+1+2+3+4
10th Apr 2019, 3:33 PM
George Samanlian