doutan5337 2014-12-01 15:58
浏览 11
已采纳

我需要帮助进行循环

hello all guys actually i am creating a code for php.

what i want to get with for loop. something will be like this .

*
**
***
****
*****
****
***
**
*

this thing i want to create right now i have this code .

<?php

    $i = 1;
    $end = 5;
    $star = "*";

    for($i; $i <= $end; $i++){
        for($b=1; $b <= $i; $b++){
            echo $star;
        }


        if($i == $end){
            for($c=1; $c <= $end; $c++ ){
                for($d=i; $d >= 2; $d--){
                    echo $star;
                }
                echo "<br>";
            }   
        }   
    };

?>

and its working fine with

*
**
***
****
*****

but then i need opposite loop first 4 then 3 then 2 then 1 ..... so please help me where i am wrong thanks for your help..

  • 写回答

7条回答 默认 最新

  • dsepcxw181184853 2014-12-01 16:10
    关注

    Using a single for loop:

    $end = 5;
    $out = array();
    
    for ($i=0;$i<$end;++$i)
    {
        $out[] = str_repeat('*', $i+1);
    }
    echo implode(PHP_EOL, $out).PHP_EOL;
    array_pop($out);
    $out = array_reverse($out);//remove last ****** <-- only one line with 5 stars
    echo implode(PHP_EOL, $out).PHP_EOL;
    

    Replace PHP_EOL with <br> if you want to, but this is the least loopy way to write this code I can think of

    live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错