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 !
9 Answers
+ 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.
+ 1
ans: 10
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
0
1997
0
10
0
10
- 1
15+1982
1997
- 2
The ans is x
is x
- 5
What output results from the following code?
<?php
$someString = "15";
$birthyear = 1982;
echo $someString + $birthyear;
?>
How to solve