For nested loops

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:

[code]for($a=1;$a<10;$a++)
{
echo “
”;

for ($b=0;$b<$a;$b++)
echo $a;

}[/code]
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.

Hi there,

[php]for($a=1;$a<10;$a++) //Sets the variable $a to 1, the commands within the curly braces {} will repeat, with $a increasing by 1 each time ($a++) until it is no longer less than 10 ($a<10)
{
echo “
”; //Echoes out a line break

for ($b=0;$b<$a;$b++)//Sets the variable $b to 0, the command below will repeat, with $b increasing by 1 each time ($b++) until it is no longer less than $a ($b<$a)
echo $a; //Echoes the contents of the variable $a

}
[/php]

If you ignore the inner for loop, the code is basically incrementing a variable from 1 to 9.

What the inner loop does, is for each value of $a, it echoes $a an amount of times equal to the value of $a. (when $a = 1, the inner loop will only run once as $b starts as 0, and cannot run the loop again or else it will stop being less than $a)

Hopefully that clears things up. Oh and FYI, underneath is a much simpler way of achieving the same thing.
[php]for($a=1;$a<10;$a++)
{
echo str_repeat($a,$a)."
";
}
[/php]

Thank you very much!
i had to understand this using FOR loop, otherwhise i would used your same code at the end.

thanks!

Sponsor our Newsletter | Privacy Policy | Terms of Service