How can I create a pyramid from using php?

前端 未结 14 1247
耶瑟儿~
耶瑟儿~ 2020-12-11 08:58

I need to create a pyramid using asterisks. I specify a value which becomes the base of the pyramid. The base contains as much asterisks as the value specified and the pyram

14条回答
  •  星月不相逢
    2020-12-11 09:25

    I think that the simplest solution is to create 2 loops with condition:

    $n = 5; // specify how many rows you want to
    $stars = 0;
    
    for ($i = $n; $i > 0; $i--) {
        for ($j = 0; $j < $i + $stars; $j++) {
            if ($j < $i - 1) {
                echo " ";
            } else {
                echo "*";
            }
        }
    
        $stars += 2;
        echo "\n";
    }
    

    The output will be:

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

提交回复
热议问题