0
PHP LOOPING
hi i got an example of looping php and im not understanding it <?php function func($arg){ $result=0; for($i=0;$i<$arg;$i++){ $result=$result+$i; } return $result; } echo func(4); ?> The output is 6 and i donât understand why Can anybody help please
3 Answers
+ 6
Here whem function is calling you passing 4 func(4)
So in arg u passed 4 and loop will work total 4 times
Initially i =0
The we will check condition
i<4 means 0<4 which is true then next line
$result=result+$i here result is 0 and i is also 0
Then $i in third step of loop here i will increase and i become 1
Then we check condition
i<4 and i =1 so 1<4 this is true so loop will run again
$result=result + i =0+1 =1 and 1 will assign to result then again i++ here i will increase again so i=2
And check condition its true so again
result=result + i ( here result is 1 and i is 2)
so result =1+2=3 result will be 3 then in $i++ here i will increase so i=3
And result 3
$result=result +i = 3+3= 6 so final value is 6
+ 2
You are calling function func() by passing the value 4 to it so your arg is 4 now.
In the for loop you assign i=0 and it should iterate till i<arg which is i<4.
In 1st iteration when i=0
result = 0+0 = 0
In 2nd iteration when i=1
result = 0+1 = 1
In 3rd iteration when i=2
result = 1+2 = 3
In 4th iteration when i=3
result = 3+3 = 6
In 5th iteration when i=4
The loop terminates because i<args fails because 4<4 is false.
So you return the result value which is 6.
+ 1
Please tag PHP instead of '/' up there â