PHP program to print a pattern of pyramid

PHPServer Side ProgrammingProgramming

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

Example

 Live Demo

<?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.

raja
Published on 02-Jul-2020 10:02:00
Advertisements