In this post we will learn to print pyramid star pattern in PHP. To create the pyramid pattern, we first inspect the structure of the pyramid. After that we try to create pyramid by programming.


How To Print Pyramid Star Pattern In PHP - 3 ?


Pyramid Star Pattern In PHP

To create  pyramid pattern in PHP, we follow the following steps:

Step 1 : First, we create a simple for loop.

<?php
    for($i=1; $i<=4; $i++) {
        echo " * ";
        echo "<br/>";
    }
?> code-box

Output :
*
*
*
*


Step 2 : To make pyramid, how many star we need in the last row of pyramid, we calculate this by this formula: (2*$n)-1. In this formula $n = total row of pyramid.

<?php
$n = 4;
for($i=1; $i<=$n; $i++) {
for($j=1;$j<=(2*$n)-1; $j++) {
echo " * ";
}
echo "<br/>";
}
?> code-box

Output :
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *


Step 3 : In this step, we will give the shape of pyramid using if condition. With the help of if condition, we control the position of star ( * ) and space (empty place). For example, empty space is coming before and after the star ( * ) in the first row. &nbsp; = For non breaking space.

<?php
$n = 4;

for($i=1; $i<=$n; $i++) {
for($j=1;$j<=(2*$n)-1; $j++) {
if($j>=$n-($i-1) && $j<=$n+($i-1)) {
echo " * ";
} else {
echo "&nbsp;&nbsp;&nbsp;";
}
}
echo "<br/>";
}
?> code-box

Output :
         *          
      * * *       
   * * * * *    
* * * * * * *


Summary

In this post we learn how to print pyramid star pattern in PHP. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post