How can I create a pyramid from using php?

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

    function create_row($num, $limit) {
    
        $append = '';
    
        if($limit > $num && ($limit - $i) % 2 == 0) {
    
            $append .= '-';
    
        }
    
        $stars = str_repeat('*', $num);
    
        $ap_len = floor(($limit - $num) / 2);
    
        $prepend = str_repeat('-', $ap_len);
    
        $append .= str_repeat('-', $ap_len);
    
        return $prepend . $stars . $append;
    
    }
    
    function create_pyramid($limit){
    
        if ($limit > 0){
    
            $no_last = false;
    
            for($i = 1; $i <= $limit; $i += 2) {
    
                print create_row($i, $limit) . PHP_EOL;
    
                if($i == $limit) {
    
                    $no_last = true;
    
                }
    
            }
    
            if(!$no_last) {
    
                print create_row($limit, $limit) . PHP_EOL;
    
            }
    
        }
    
    }
    
    create_pyramid(10);
    

提交回复
热议问题