1

please someone can explain me in detailed way how this loop in php works?

for($a=1;$a<10;$a++) 
{
    echo "<br>";

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

}

Why the output is 1 22 333 4444 55555 etc and not just 1 2 3 4 5 and so on, i know is something elementary but i cannot get it.

thank you.

1
  • You're expecting the output to be 1 2 3 4 5? Commented Mar 27, 2011 at 15:56

3 Answers 3

6

The key is the $a in the inner loop.

for ($b=0;$b<$a;$b++) 
             ^-------------- HERE 

this will count from zero to $a (which is increased every time) in every loop and output $a as many times.

 $a = 0:  no output (inner loop runs from 0 to 0)
 $a = 1:  1 output  (inner loop runs from 0 to 1)
 $a = 2:  2 outputs (inner loop runs from 0 to 2)
 $a = 3:  3 output  (inner loop runs from 0 to 3)
 etc.....
Sign up to request clarification or add additional context in comments.

Comments

2

There are two loops in your code, the outer loop initialize the value of $a as 1

$a = 1;

Then in the inner loop $b is set to 0

$b = 0;

The condition for the inner loop to succeed in its first execution is

$b < $a 

Or if you don't follow it,

0 < 1

Because remember the inner loop initialize $b as 0, and $a is initialized in the outer loop as 1

So 0 is less that 1, so it will succeed and execute

echo $a; // 1

The inner loop will only execute it 1 time because in its second iteration $b is already 1

$b++

Now it will go to the outer loop again, and $a will equal to 2 because the for loop just did

$a++

2 is less than 10 so it will execute the second loop again. But now the second loop is condition changes because

$b < $a // 0 < 2

Because remember $a is now equal to 2! So the condition succeed and it will execute

echo $a // or 2

Then after executing in its first try, the for loop will do $b++ so $b will become 1.

SO now, the for loop will test the condition again and the result will be

$b < $a // 1 < 2

1 is less than 2 so it will execute the echo statement again

echo $a // 2

Hence you get 22

Then after that the for loop will do $b++, so now $b is 2 already! Because 2 is not less than 2, hence it will fail and go to the outer loop again.

Comments

1

Each time through the outer loop, the inner loop is performed a times. So 1 is echoed once, 2 is echoed twice, and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.