How can I create a pyramid from using php?

前端 未结 14 1228
耶瑟儿~
耶瑟儿~ 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:28

    You can try

    create_pyramid("*", 5);
    create_pyramid("@", 10);
    create_pyramid("^_^", 10);
    
    function create_pyramid($string, $level) {
        echo "
    ";
        $level = $level * 2;
        for($i = 1; $i <= $level; $i ++) {
            if (!($i % 2) && $i != 1)
                continue;   
            print str_pad(str_repeat($string, $i),($level - 1) * strlen($string), " " , STR_PAD_BOTH);
            print PHP_EOL;
        }
    }
    

    Output A

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

    Output B

             @         
            @@@        
           @@@@@       
          @@@@@@@      
         @@@@@@@@@     
        @@@@@@@@@@@    
       @@@@@@@@@@@@@   
      @@@@@@@@@@@@@@@  
     @@@@@@@@@@@@@@@@@ 
    @@@@@@@@@@@@@@@@@@@
    

    Output C

                            ^_^^_^^_^                        
                         ^_^^_^^_^^_^^_^                     
                      ^_^^_^^_^^_^^_^^_^^_^                  
                   ^_^^_^^_^^_^^_^^_^^_^^_^^_^               
                ^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^            
             ^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^         
          ^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^      
       ^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^   
    ^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^^_^
    

提交回复
热议问题