Print star pattern in PHP

star pattern in php

Know how to print star pattern in php

To print a star pattern in PHP, we can use nested loops. The outer loop will iterate over the rows of the pattern, and the inner loop will iterate over the columns of each row.

Pyramid star pattern:

<?php
$size = 5; // number of rows in the pyramid
for ($i = 0; $i < $size; $i++) {
  // print spaces before the stars
  for ($j = 0; $j < $size - $i - 1; $j++) {
    echo " ";
  }
  // print stars for this row
  for ($j = 0; $j < 2 * $i + 1; $j++) {
    echo "*";
  }
  // move to the next line
  echo "\n";
}
?>
  • First, we set the number of rows we want to print in the pyramid by setting the $size variable.
  • Then, we use a for loop to iterate over each row of the pyramid. The loop variable $i starts at 0 and goes up to $size - 1.
  • Inside the outer loop, we use another for loop to print the spaces before the stars on each row. We calculate the number of spaces we need by subtracting the current row number $i from $size, and then subtracting 1 to account for the first star.
  • After printing the spaces, we use another for loop to print the stars for this row. We calculate the number of stars we need by multiplying the current row number $i by 2 and adding 1 to account for the middle star.
  • Finally, we move to the next line by using the echo function to print a newline character \n.

When you run this code, you should see the following output:

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

Right Triangle Pattern:

<?php
$size = 5; // number of rows in the triangle
for ($i = 0; $i < $size; $i++) {
  for ($j = 0; $j <= $i; $j++) {
    echo "*";
  }
  echo "\n";
}
?>

Output:

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

Inverted Right Triangle Pattern:

<?php
$size = 5; // number of rows in the triangle
for ($i = 0; $i < $size; $i++) {
  for ($j = $size - $i; $j > 0; $j--) {
    echo "*";
  }
  echo "\n";
}
?>

Output:

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

Diamond Pattern:

<?php
$size = 5; // number of rows in the diamond
for ($i = 0; $i < $size; $i++) {
  // print spaces before the stars
  for ($j = 0; $j < $size - $i - 1; $j++) {
    echo " ";
  }
  // print stars for this row
  for ($j = 0; $j < 2 * $i + 1; $j++) {
    echo "*";
  }
  // move to the next line
  echo "\n";
}
for ($i = $size - 2; $i >= 0; $i--) {
  // print spaces before the stars
  for ($j = 0; $j < $size - $i - 1; $j++) {
    echo " ";
  }
  // print stars for this row
  for ($j = 0; $j < 2 * $i + 1; $j++) {
    echo "*";
  }
  // move to the next line
  echo "\n";
}
?>

Output:

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

Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories