dragon8002 2016-06-29 10:53
浏览 78

PHP嵌套while循环

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++;
}
  • 写回答

4条回答 默认 最新

  • dpzo13732 2016-06-29 10:56
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题