In this post we will learn to print diamond star pattern in PHP. Let's see how we make this.


How To Print Diamond Star Pattern In PHP - 7 ?


Diamond Star Pattern In PHP

To create diamond star pattern in PHP we will follow the following steps:


Step 1: The diamond star pattern looks as if a straight pyramid is placed on top of an inverted pyramid. We know how to create pyramid star pattern in PHP, if you do not know this, then you first read this post Pyramid Star Pattern In PHP.

<?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 :
          *          
       * * *       
    * * * * *    
* * * * * * *

Step 2: In this step, we create another pyramid pattern under this pyramid pattern and copy paste the same pyramid pattern code. Then we get this output.

<?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/>";
}

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 :
          *          
       * * *       
    * * * * *    
* * * * * * *

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


Step 3: In this step, we reverse the pyramid below. For this, we make changes in the for loop. Then we get the diamond star pattern in the output.


<?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/>";
}

for($i=($n-1); $i>=1; $i--) {  //make changes in this for loop
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 diamond 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