Jump to content

For nested loop


phpnub2

Recommended Posts

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.

 

 

Link to comment
https://forums.phpfreaks.com/topic/231840-for-nested-loop/
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/231840-for-nested-loop/#findComment-1192866
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/231840-for-nested-loop/#findComment-1192873
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.