Computer >> Computer tutorials >  >> Programming >> PHP

PHP program to print a pattern of pyramid


Let us see an example to print a pattern of pyramid in PHP −

Example

<?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 "\n";
   }
}
$val = 7;
print_pattern($val);
?>

Output

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

A function named ‘print_pattern’ is defined that iterates through the number of rows through which the pattern needs to be generated. Relevant line breaks are also echoed using the ‘echo’ attribute. The function is called by passing the number of rows for which the pattern needs to be generated.