Can someone explain to me how this code works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone explain to me how this code works?

<?php function loop(){ static $a = 1; $b = 1; $a++; $b++; return $a.$b; } for($i = 0;$i < 3;$i++) loop(); echo loop(); ?>

5th Sep 2018, 5:32 PM
Hércules de Lima Coelho
Hércules de Lima Coelho - avatar
3 Answers
+ 5
You can see info about static variables here https://www.tutorialspoint.com/php/php_static_variables.htm. When a variable is declared static the value is stored after each operation. It's exactly the opposite when the variable is not static. The value is lost on system exit of the function. So in the loop we call the loop function 3 times => the value of "a" becomes 4, the value of "b" is not stored so it becomes 2. After that we call again loop function when printing => "a" is now 5, "b" can't be more than 2 as its value is not stored. At the end concatenate "a" and "b" => 52. You can see the result of the code here https://code.sololearn.com/w1ok42ja24RG/?ref=app
5th Sep 2018, 7:45 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 3
You are welcome :)
6th Sep 2018, 6:53 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
Thank you so much :D
6th Sep 2018, 4:07 AM
Hércules de Lima Coelho
Hércules de Lima Coelho - avatar