PHP Program to Print Pyramid Pattern
for loops in PHP to print spaces and stars for each row, like for ($i = 1; $i <= $rows; $i++) { for ($j = $rows; $j > $i; $j--) echo ' '; for ($k = 1; $k <= 2 * $i - 1; $k++) echo '*'; echo "\n"; } to print a pyramid pattern.Examples
How to Think About It
Algorithm
Code
<?php $rows = 5; for ($i = 1; $i <= $rows; $i++) { for ($j = $rows; $j > $i; $j--) { echo ' '; } for ($k = 1; $k <= 2 * $i - 1; $k++) { echo '*'; } echo "\n"; } ?>
Dry Run
Let's trace the pyramid pattern for 3 rows through the code.
Row 1
Spaces: 2 (because 3 - 1), Stars: 1 (2*1 - 1), Output: ' *'
Row 2
Spaces: 1 (3 - 2), Stars: 3 (2*2 - 1), Output: ' ***'
Row 3
Spaces: 0 (3 - 3), Stars: 5 (2*3 - 1), Output: '*****'
| Row | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
Why This Works
Step 1: Print spaces first
We print spaces first to push stars to the right, creating the pyramid shape. The spaces decrease each row using $rows - $i.
Step 2: Print stars next
Stars increase by two each row using 2 * $i - 1, making the pyramid wider as we go down.
Step 3: Move to next line
After printing spaces and stars for a row, we print a newline \n to start the next row below.
Alternative Approaches
<?php $rows = 5; $i = 1; while ($i <= $rows) { $j = $rows; while ($j > $i) { echo ' '; $j--; } $k = 1; while ($k <= 2 * $i - 1) { echo '*'; $k++; } echo "\n"; $i++; } ?>
<?php $rows = 5; for ($i = 1; $i <= $rows; $i++) { echo str_repeat(' ', $rows - $i); echo str_repeat('*', 2 * $i - 1); echo "\n"; } ?>
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops: one for rows and two inner loops for spaces and stars, each up to n, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space for counters and prints directly, so space complexity is O(1).
Which Approach is Fastest?
Using str_repeat is more concise and may be slightly faster due to internal optimizations, but all approaches have similar O(n^2) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Clear control and beginner-friendly |
| While loops | O(n^2) | O(1) | Alternative loop style |
| str_repeat function | O(n^2) | O(1) | Concise and readable code |