Shawon
Shawon

Reputation: 1030

PHP: Generate a dynamic numeric Pyramid

This is a normal pyramid horizontal block dynamic like hor = 5

$k = 10;
$last = 2;
    for($i=0;$i<=$last;$i++){

        for($t = 1;$t <= $last-$i;$t++)
        {
            echo "&nbsp;&nbsp;";
        }
        for($j=1;$j<=$i+$i;$j++)
        {
            $k--;
            echo "$k&nbsp;&nbsp;";
        }
    echo "<br>";

but i need this out put :

enter image description here

Is it possible? any help Appreciated. thank you.

Upvotes: 0

Views: 628

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

Here's a much tidier way to do it:

First, generate your pyramid array:

$width = 5;
$pyramid = array();
$number = 0;
while($width > 0) {
    $row = array();
    for( $i=0; $i<$width; $i++) {
        $row[] = ++$number;
    }
    $pyramid[] = $row;
    $width -= 2;
}

This will give you the pyramid in an array from bottom to top. So just flip it over:

$pyramid = array_reverse($pyramid);

And now render it:

echo '<div style="text-align:center">';
foreach($pyramid as $row) {
    echo implode(" ",$row).'<br />';
}
echo '</div>';

Upvotes: 6

Related Questions