In this post, we will learn to print star pattern in PHP. This question is usually asked at the time of interviews. For this reason it becomes very important that we know how to create a star pattern in PHP. Star patterns can be created not only in PHP but also in c / c ++ and java, the only difference will be the syntax of the code.


To create a star pattern we need to have a good knowledge of nested loops. For this, we use nested for loop. This pattern can make a programmer who has a good understanding of programming.


How To Print Star Pattern In PHP - 1 ?


Print Star Pattern In PHP

To print the star pattern in PHP we will use nested for loop and then echo "*". We can see this in following code:


<?php

for ($i = 1; $i <= 5; $i++) {

for( $j = 1; $j<= $i; $j++) {

echo " * ";

}

echo "<br/>";

}

?> code-box



Code Explanation :

We will understand the above code in the following steps:

  • When the first loop runs, the value of $i is 1. Then when it enters the second loop the value of $j is 1 and this condition returns $ j <= 1 to true and then one star is printed. Then when this loop runs for the second time it becomes $j = 2 due to which the condition of $ j <= 1 becomes false, then this loop closes and it comes out of the loop then starts from the new line.
  • Then the outside loop runs for the second time, becoming $i = 2 and when it enters the second loop it becomes $j <= 2. For this reason, this loop now runs twice and after printing two stars, it comes out of the loop and then starts from the new line. In this way, these loops continue to run and the star continues to print.



Print Number Pattern In PHP

There are two types of Number Pattern:

Pattern 1 (1 - 1 2 - 1 2 3)

If we want to print the number instead of star, then for this we have to place $j instead of star. Then as the loop runs, the value of  $j will be printed and the number pattern will be printed. 

The code of the number pattern is as follows:


<?php

for ($i = 1; $i <= 5; $i++) {

for( $j = 1; $j<= $i; $j++) {

echo $j  . " ";

}

echo "<br/>";

}

?> code-box



Pattern 2 (1 - 2 2 - 3 3 3)

Replacing $j with $i then we get this pattern:

<?php

for ($i = 1; $i <= 5; $i++) {

for( $j = 1; $j<= $i; $j++) {

echo $i  . " ";

}

echo "<br/>";

}

?> code-box


Summary

In this post we learn how to print 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