PHP program to print a pattern of pyramid

In PHP, you can print a pyramid pattern using nested loops. The pattern involves printing spaces for centering and asterisks to form the pyramid shape.

Example

Here's how to create a pyramid pattern using a function −

<?php
function print_pattern($val)
{
    $num = 2 * $val - 2;
    for ($i = 0; $i < $val; $i++)
    {
        for ($j = 0; $j < $num; $j++)
            echo " ";
        $num = $num - 1;
        for ($j = 0; $j <= $i; $j++ )
        {
            echo "* ";
        }
        echo "<br>";
    }
}
$val = 7;
print_pattern($val);
?>

Output

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

How It Works

The print_pattern() function creates a pyramid by:

  • Calculating spaces: $num = 2 * $val - 2 determines initial spacing
  • Outer loop: Controls the number of rows ($val)
  • First inner loop: Prints spaces for centering the pyramid
  • Second inner loop: Prints asterisks for each row (incrementing by 1 each time)

Alternative Pattern

You can also create a solid pyramid without spaces between asterisks −

<?php
function solid_pyramid($rows)
{
    for ($i = 1; $i <= $rows; $i++) 
    {
        // Print spaces
        for ($j = 1; $j <= $rows - $i; $j++) 
        {
            echo " ";
        }
        // Print asterisks
        for ($k = 1; $k <= (2 * $i - 1); $k++) 
        {
            echo "*";
        }
        echo "<br>";
    }
}

solid_pyramid(5);
?>
    *
   ***
  *****
 *******
*********

Conclusion

PHP pyramid patterns use nested loops to control spacing and asterisk placement. The key is calculating proper spacing and incrementing the number of asterisks per row to create the pyramid shape.

Updated on: 2026-03-15T09:02:46+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements