Home >>PHP Tutorial >Print star pattern in PHP

Print star pattern in PHP


Print Pattern in PHP

In this following tutorial, you will learn about the process to print star pattern in PHP. These are the questions that are generally asked in the interviews and should be learned. These questions are generally solved by the people that are having a great understanding of the nested loops.

This concept of star pattern program in PHP can also be used to solve various problems in C/C++/Java and any other programming languages, the difference will of the syntax of the codes.

This tutorial will guide you about the star print program in PHP and all the different methods and the various patterns that are involved in this subject.

Here are the more than 10 start pattern that will be covered in this tutorial:

Pattern 1

<?php	
for ($i=1; $i<=5; $i++)	
{	 
for($j=1;$j<=$i;$j++)	  
{	  	
echo $j." ";	 
}	  	
echo "<br/>";   	
}  
?>
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Pattern 2

<?php	
for ($i=1; $i<=5; $i++)	
{	 
for($j=1;$j<=$i;$j++)	  
{	  	
echo $i." ";	 
}	  	
echo "<br/>";   	
}  
?>
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Pattern 3

<?php	
for ($i=1; $i<=5; $i++)	
{	 
for($j=1;$j<=$i;$j++)	  
{	  	
echo " * ";	 
}	  	
echo "<br/>";   	
}  
?>
Output
*
* *
* * *
* * * *
* * * * *

Pattern 4

<?php	
for ($i=1; $i<=5; $i++) 	       
{ 	 
for ($k=5; $k>$i; $k--)	 
{	  
//print one space throgh html ;
echo " ";	  
}	
for($j=1;$j<=$i;$j++)	  
{	  	
echo "*";	  
}	  	
echo "<br/>";	
} 
?>
Output
     *
    * *
   * * *
  * * * *
 * * * * *

Pattern 5

<?php  
for($i=0;$i<=5;$i++)
{  
for($j=5-$i;$j>=1;$j--)
{  
echo "* ";  
}  
echo "<br>";  
}  
?>  
Output
* * * * *
* * * *
* * *
* *
*

Pattern 6

<?php  
for($i=0;$i<=5;$i++)
{  
for($k=5;$k>=$i;$k--)
{  
echo "  ";  
}  
for($j=1;$j<=$i;$j++)
{  
echo "*  ";  
}  
echo "<br>";  
}  
for($i=4;$i>=1;$i--)
{  
for($k=5;$k>=$i;$k--)
{  
echo "   ";  
}  
for($j=1;$j<=$i;$j++)
{  
echo "*  ";  
}  
echo "<br>";  
}  
?>  
Output

Pattern 7

<?php  
for($i=1; $i<=5; $i++)
{   
for($j=1; $j<=$i; $j++)
{   
echo ' * ';   
}  
echo '<br>';   
}  
for($i=5; $i>=1; $i--)
{   
for($j=1; $j<=$i; $j++)
{  
echo ' * ';   
}   
echo '<br>';   
}   
?>  
Output

Pattern 8

<?php  
for($i=5; $i>=1; $i--)  
{  
if($i%2 != 0)  
{  
for($j=5; $j>=$i; $j--)  
{  
echo "* ";  
}  
echo "<br>";  
}  
}  
for($i=2; $i<=5; $i++)  
{  
 if($i%2 != 0)  
{  
 for($j=5; $j>=$i; $j--)  
{  
echo "* ";  
}  
echo "<br>";  
}  
}  
?>  
Output

Pattern 9

<?php
for ($row=1; $row<=3; $row++)
	{
	for ($column=1; $column<=3; $column++)
	{
	echo  $row*$column." ";
	}
	echo "<br>";

}
?>
Output :
1 2 3
2 4 6
3 6 9

Pattern 10

<?php
$x=1;
for($i=1;$i<=3;$i++)
{
	for($j=1;$j<=3;$j++)
	{
	echo $x++;	
	}		
	echo "<br>";
}
?>
Output :
1 2 3
4 5 6
7 8 9

Pattern 11

<?php
$j = 1;
	 $x = 0;
	for($i = 1; $i <=3; $i++) 
	{
		while($x < 3) 
		{
			echo $j++;
			$x++;
		}
		$x = 0;
		echo "<br>";
	}
?>
Output :
1 2 3
4 5 6
7 8 9

Popular Tutorials