In this post we will learn to create rectangle star pattern in PHP. Printing rectangle pattern is a bit tricky but also very easy.


How To Print Rectangle Star Pattern In PHP - 5 ?


Rectangle Star Pattern In PHP

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


Step 1: In this step we take a variable $n and give it value 5. Then run a for loop and we get an output of 5 star in column.

<?php

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

echo "*";
echo "<br/>";

}

?> code-box

Output :
*
*
*
*
*

Step 2: In this step we take another for loop inside the first for loop and we get following output.

<?php

$n = 5;
for($i = 1; $i <= $n; $i++) {
for($j = 1; $j <= $n; $j++) {
echo "*";

}
echo "<br/>";

}

?> code-box

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

Step 3: Now we only want the star of  the first column and the last column. For this we take if condition and get the following output.

<?php

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

if($j == 1 || $j == $n) {
echo "*";
} else {
echo "&nbsp;&nbsp;";
}
}
echo "<br/>";

}

?> code-box

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

Step 4: Now we want the horizontal stars between these two columns of the star. For this we take another if condition in else part of first if condition and get rectangle star pattern as an output.

<?php

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

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

Summary

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