Star pattern programs in PHP

To get command over language like php,C,Java, python etc to build strong logic one should master different type of pattern printing program.

It will strong your grip on different type of loop like for loop, while loop,foreach loop, do-while loop etc.

We will practice some star pattern program in PHP

PHP program to print Right Triangle :

<?php
/******************************************************************************

           PHP program to print Right Triangle

*******************************************************************************/


for($row=1;$row<=6;$row++)
{
   for ($col=1;$col<=$row;$col++)
    {
     echo "*";
        if($col< $row)
         {
           echo " ";
         }
     }
 echo "\n";
}
?>

Output :

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

Program to print Inverted Right Triangle in PHP :

<?php
/******************************************************************************

           PHP program to print Inverted Right Triangle

*******************************************************************************/

for ($row = 1; $row <= 6; $row++)
{
    for ($col = 1; $col <= ($row > 3 ? 7 - $row : $row); $col++)
    {
        echo '* ';
    }
 
    echo "\n";
 
}


?>

Output :

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

PHP program to print Alphabet pattern ‘A’ :

<?php
/******************************************************************************

           PHP program to print Alphabet pattern 'A'

*******************************************************************************/


 for ($row=0; $row<=6; $row++)
{
  for ($col=0; $col<=6; $col++)
    {
        if ((($col == 1 or $col == 5) and $row != 0) or (($row == 0 or $row == 3) and ($col > 1 and $col < 5)))
            echo "*";    
        else  
            echo " ";     
    }        
  echo "\n";
}
 
?>

Output :

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

PHP program to print Alphabet pattern ‘B’ :

 <?php
/******************************************************************************

           PHP program to print Alphabet pattern 'B'

*******************************************************************************/

for ($row=0; $row<7; $row++)
{
  for ($col=0; $col<=7; $col++)
    {
      if ($col == 1 or (($row == 0 or $row == 3 or $row == 6) and ($col < 5 and $col > 1)) or ($col == 5 and ($row != 0 and $row != 3 and $row != 6)))
            echo "*";    
        else  
            echo " ";  
    }        
  echo "\n";
}
?>

Output :

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

Share This!

Leave a Reply

Your email address will not be published.