PHP Program to print the star pattern


April 13, 2022, Learn eTutorial
1066

What is a star pattern?

In this program, we are printing the star in the pattern. Here we use the iterated  for loop . For example, if we want to print the 5 rows the first row will have 1 start the second star have 2 stars the third start has 3 starts, and so on till the fifth row.

How to print star patterns using PHP

To print the star in PHP we first read the number of rows from the user and perform iterative for loop and print '*' according to the number of rows.

ALGORITHM

Step 1: Read the number of rows into the variable rows

Step 2: Assign the value 1 into the variable and perform step 3 until the condition 'i <= rows' becomes false and increment the value of  variable i by 1 and print a new line in every iteration

Step 3: Assign the value 1 into the variable and perform the sub-step until the condition 'j <= i' becomes false and increment the value of the variable j by 1 in every iteration

        (i) print '*'

PHP Source Code

                                          <?php
$rows = readline("Enter the number of rows: ");
for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo " * ";
    }
    echo "\n";
}
?>
                                      

OUTPUT

Enter the number of rows: 10
 *
 *  *
 *  *  *
 *  *  *  *
 *  *  *  *  *
 *  *  *  *  *  *
 *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *  *  *