1

I tried to do a while inside a while to print a multiplication table like,

1  2  3  4  5
2  4  6  8 10
3  6  9 12 15
4  8 12 16 20
5 10 15 20 25

But I got only 1, 2, 3, 4, 5.

Code:

$i = 1;
$x = 1;
while($i <= 5){
   while($x <= 5){
     echo $i * $x;
     $x++;
   }
   echo "<br>";
   $i++;
}
3
  • 5
    You need to reset $x (missing $x =..). Commented Jun 29, 2016 at 10:54
  • 1
    Some sensible code indentation would be a good idea. It help us read the code and more importantly it will help you debug your code Take a quick look at a coding standard for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. Commented Jun 29, 2016 at 10:56
  • Amout of same answers is really high. Commented Jun 29, 2016 at 11:00

4 Answers 4

3

This is happening because you're not resetting $x when the inner loop completes its iteration. Try this instead:

$i = 1;
while($i <= 5) {
  $x = 1;
  while($x <= 5) {
    echo $i * $x;
    $x++;
  }
  echo "<br>";
  $i++;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You need to reset $x, so:

$i = 1;
$x = 1;
while($i <= 5){
    while($x <= 5){
        echo $i * $x;
        $x++;
    }
    $x = 1; // added this line
    echo "<br>";
    $i++;
}

Output:

12345
246810
3691215
48121620
510152025

You can then do what ever you want to format it.



More elabrate explanation:

  • First run:

It enters both outer and inner loops, showing the desired output for the first line. You end up with $i = 2 and $x = 6.


  • Second run:

Since $i is 2, it doesn't leave the outer loop, but $x is 6, so it doesn't enter the inner loop again.


  • Last* run:

It then keeps adding 1 to $i until it doesn't match the outer loop condition anymore and leaves you with that unwanted result.

1 Comment

This could also be achieved using for: https://3v4l.org/s7fJE
1

Use this

This is because you have not initialized your $x after external while loop completes its one cycle. so after one cycle inner loops does not run

<?php
$i = 1;
while($i <= 5) {
  $x = 1;
  while($x <= 5) {
    echo $i * $x;
    $x++;
  }
  echo "<br>";
  $i++;
}

1 Comment

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.
0

DEMO ONLINE

php code:

$i = 1;
while($i <= 5){
  $x = 1;
  while($x <= 5){
    echo $i * $x." ";
    $x++;
  }
  echo "<br/>";
  $i++;
}

result:

1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 

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.