Need help with a loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Need help with a loop

Function loop(){ Static $a=1; $b=1; $a++; $b++; Return $a.$b; } For($i=0; $i<3; $i++) Loop(); Echo loop(); The output is 52. I tried to understand why but i need help. So the loop will be executed 2 times. First output will be 22. In the second one $a=2(because it is static) and $b=1. So the output will be 21( from my humble knowledge) Then the loop will stop because $i=3. I am really confused. Thank you.

13th Aug 2018, 9:21 PM
razvan
razvan - avatar
6 Answers
+ 6
good day, razvan ! The $a variable is "static", so the first call of loop() $a=2,$b=2 the 2-nd call of loop() $a=3,$b=2 the 3-rd call of loop() $a=4,$b=2 the 4-th call of loop() $a=5,$b=2 and function returns 52
19th Aug 2018, 10:36 PM
Dmitriy
Dmitriy - avatar
+ 4
right..so every time when the loop starts $a will be equal to 1+ the last value of $a. Thank you Dmitriy!
19th Aug 2018, 10:41 PM
razvan
razvan - avatar
+ 3
:)) the question was why the output is 52. if somebody can explain me how php got this result. thank you
14th Aug 2018, 10:18 AM
razvan
razvan - avatar
+ 3
razvan , good luck!
19th Aug 2018, 10:48 PM
Dmitriy
Dmitriy - avatar
+ 1
The function loop() is executed 3 times in the for. The value for $a is 4 and $b is 2. When you use echo the function loop() is executed one more time, and the value for $a change to 5
24th Aug 2018, 3:05 PM
Emmanuel
0
what are you tying to archive here?
14th Aug 2018, 10:12 AM
Ben Nxumalo
Ben Nxumalo - avatar