"" /> "" /> ""/>

How I can make pattern Pyramid number php like this

56 Views Asked by At

How I can make pyramid number like this

    1
   212
  32123

Code:

<?php
    
for($i=2; $i<=5; $i++){
    for($x=$i; $x>=2; $x--){    
        echo "$x&nbsp;&nbsp;";    
    }
    echo "<br/>";    
}

for($i=1; $i<=5; $i++){
    for($x=1; $x<=$i; $x++){
        echo "$x&nbsp;&nbsp";
    }
    echo "<br/>";
}
1

There are 1 best solutions below

0
nice_dev On

You seem to printing numbers in descending order, adding a new line and then go to print numbers in ascending order in another line. This makes it too late to do so since you already lost the current line.

Instead, for every row, go from row number till 1 and print numbers and repeat the same in the same line from 2 till row number and then add a new line like below:

<?php
 
function printPyramid($rows){
    for($i = 1; $i <= $rows; ++$i){
        echo str_repeat("&nbsp;", $rows - $i);
        
        for($j = $i; $j >= 1; --$j){
            echo $j;
        }
        
        for($j = 2; $j <= $i; ++$j){
            echo $j;
        }
        
        echo PHP_EOL; // or echo "<br/>";
    }
} 
    
printPyramid(7);

Online Demo (view the output in HTML format by clicking on the eye icon)