0

What output results from the following code?

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); -------------------------------------------------------- The output is "10" but why and how ?! i dont understand !

30th Dec 2017, 1:35 AM
alireza naderi
alireza naderi - avatar
9 Réponses
+ 10
Follow the loop and track every iteration. i=0 : 0+0=0 i=1 : 0+1=1 i=2 : 1+2=3 i=3 : 3+3=6 i=4 : 6+4=10 i=5 : nothing happens because i is no longer less than 5. Final result 10.
30th Dec 2017, 3:15 AM
Kevin Gilkey-Graham
Kevin Gilkey-Graham - avatar
+ 1
ans: 10
28th Jul 2020, 11:14 AM
sonajosf
sonajosf - avatar
0
Add a little verbosity to your code, I guess it will explain itself better than I could : ) <?php function func($arg) { $result = 0; for($i=0; $i<$arg; $i++) { echo "\$result ($result) + \$i ($i) = "; $result = $result + $i; echo "$result<br />"; } return $result; } echo func(5); ?> Hth, cmiiw
30th Dec 2017, 3:31 AM
Ipang
0
1997
7th Mar 2021, 11:17 AM
Junaid Ul Islam
Junaid Ul Islam - avatar
0
10
17th May 2022, 6:34 AM
Megha Raj kandel
0
10
9th Jun 2022, 9:30 PM
Algorithm
Algorithm - avatar
- 1
15+1982 1997
31st Aug 2019, 11:51 AM
lakshmi tulasi javvadi
lakshmi tulasi javvadi - avatar
- 2
The ans is x is x
7th Jul 2020, 8:08 PM
Faith Mundi
Faith Mundi - avatar
- 5
What output results from the following code? <?php $someString = "15"; $birthyear = 1982; echo $someString + $birthyear; ?> How to solve
22nd Aug 2019, 1:53 AM
उमेश रूचाल
उमेश रूचाल - avatar