Pyramid Star Pattern in PHP

What You'll Learn
This program prints a centered pyramid by printing spaces first and then an odd number of stars.
Row $i prints $rows - $i spaces and 2 * $i - 1 stars.
⭐ Pattern Output
When you run the program with rows = 5:
*
***
*****
*******
*********Complete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}
for ($j = 1; $j <= 2 * $i - 1; $j++) {
echo "*";
}
echo PHP_EOL;
}🧠 How It Works
Setup
$rows is the pyramid height. for ($i = 1; $i <= $rows; $i++) walks from one star on row 1 to a bottom row of 2 * $rows - 1 stars. Two inner loops both use $j—first spaces, then stars.
Margin: echo " "
for ($j = 1; $j <= $rows - $i; $j++) prints $rows - $i spaces so the odd-width star block sits centered.
Stars: echo "*"
for ($j = 1; $j <= 2 * $i - 1; $j++) prints 1, 3, 5, …, 2*$rows-1 asterisks. Or echo str_repeat(" ", $rows - $i) . str_repeat("*", 2 * $i - 1) . PHP_EOL;.
New line
echo PHP_EOL; ends the row. Row $i prints ($rows - $i) + (2 * $i - 1) = $rows + $i - 1 characters before the newline.
Symmetric pyramid
Total stars n² (sum of odd lengths 1 through 2n-1); O(n²) output for n = $rows, O(1) extra space. The bottom row scrolls horizontally in the green preview on narrow screens. Same core loops as the top half of Program 10.
Variation — User Input (CLI) Version
Read rows from standard input (works when you run the file from terminal using php):
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}
for ($j = 1; $j <= 2 * $i - 1; $j++) {
echo "*";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print the inverted pyramid by reversing the outer loop and adjusting star counts (Program 6)
- Combine pyramid + inverted pyramid to form a filled diamond
- Build each row using
str_repeat()for simpler code - Print a hollow pyramid (stars only at the edges)
- Validate
$rows > 0before printing
Avoid
- Using even star counts (the pyramid won’t stay centered)
- Forgetting spaces before stars (pattern shifts left)
- Off-by-one mistakes in
2 * $i - 1 - Mixing tabs and spaces (alignment changes by font)
- Assuming user input is always valid
Key Takeaways
Centering uses $rows - $i spaces before the stars.
Row $i prints 2 * $i - 1 stars (odd counts keep symmetry).
Each next row adds 2 stars and removes 1 leading space.
Time complexity is O(n²) for n rows.
This is the building block for diamonds (pyramid + inverted pyramid).
❓ Frequently Asked Questions
Next: Inverted Pyramid Pattern
Continue to Program 6 to print the inverted pyramid star pattern in PHP.
If you print this pyramid and then print Program 6, you get a filled diamond (Program 10).
12 people found this page helpful
