简体   繁体   中英

PHP nested while loop

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++;
}

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++;
}

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.

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++;
}

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM