Vimal Basdeo Vimal Basdeo - 6 months ago 14
PHP Question

How can I create a pyramid from using php?

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 pyramid must skip its rows by 1..Here I am facing a problem when I specify an even number of base..

The pyramid must looke like the one below.

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


I am getting

####*
###***
##*****
###*****
####*****
**********


I want to replace the # by some blank space and I am getting the bug that the number of asterisks in the 4th row has decreased.. How do I fix these two bugs ?

function create_pyramid($limit){

if ($limit > 0){
for ($row =0;$row<=$limit;$row++){
if (($row % 2 == 0) && ($row != $limit)){ continue;}
$rows = "";
for ($col =0;$col<$row;$col++){
$rows= $rows.'*';
}
$pattern = "%'#".((($limit - $row)/2)+$row)."s\n";
printf ($pattern,$rows);
print '<br />';
}
}
else{
print "Invalid data";
}
}

create_pyramid(10);

Nin Nin
Answer

Just make it simpler:

function create_pyramid($limit) {
    for($row = 1; $row < $limit; $row ++) {
        $stars = str_repeat('*', ($row - 1) * 2 + 1);
        $space = str_repeat(' ', $limit - $row);
        echo $space . $stars . '<br/>';
    }
}
echo "<pre>" ;
create_pyramid(10);
Comments