phpnub2 Posted March 27, 2011 Share Posted March 27, 2011 Hello i am new here, and new to php too. I try to learn php from about 20 days, and i am getting stuck in something, somebody asked me to make a program that will produce the following output, i have to use a nested for loop: 1 22 333 4444 55555 ........etc The code for is: for($a=1;$a<10;$a++) { echo "<br>"; for ($b=0;$b<$a;$b++) echo $a; } I do know this is something elementary, but really i cannot understand how it works is there any saint that will comment the code and explain step by step whats happening there? Thank you. Quote Link to comment Share on other sites More sharing options...
sunfighter Posted March 27, 2011 Share Posted March 27, 2011 You have an outside loop and an inside loop. Each time the outside loop executes the inside loop spins through its entire range. So the outside steps one at a time; the inside spins. Your outside loop is "for($a=1;$a<10;$a++)" it will step from 1 to 9 and gives that value to $a. The inside loop is "for ($b=0;$b<$a;$b++)" it goes from zero to one less than $a (which is determined by the outside loop) Or we can say it spins $a times. First step $a = 1, the inside loop spins once and prints $a which is 1. Second step of the outside loop is $a = 2. Inside loop spins from $b = 0 to $b = 1. Two times and prints $a (2) twice. Third step $a = 3 and $b goes from 0 to 2 (3X) and prints $a (3) three times. etc.. hope this helps Quote Link to comment Share on other sites More sharing options...
chris.smith Posted March 27, 2011 Share Posted March 27, 2011 Hello i am new here, and new to php too. I try to learn php from about 20 days, and i am getting stuck in something, somebody asked me to make a program that will produce the following output, i have to use a nested for loop: 1 22 333 4444 55555 ........etc The code for is: for($a=1;$a<10;$a++) { echo "<br>"; for ($b=0;$b<$a;$b++) echo $a; } I do know this is something elementary, but really i cannot understand how it works is there any saint that will comment the code and explain step by step whats happening there? Thank you. In addition to what sunfighter said, the nested loop still acts even though it doesn't have the curly brackets ({ and }) after it. Quote Link to comment Share on other sites More sharing options...
phpnub2 Posted March 28, 2011 Author Share Posted March 28, 2011 thank you all. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.