Inverted Right-Aligned Triangle Star Pattern in PHP

What You'll Learn
This program prints an inverted right-aligned triangle. The first row prints rows stars, and each next row prints one less star, while leading spaces increase to keep the right edge aligned.
For row $i (from $rows down to 1), print $rows - $i spaces and then print $i stars.
⭐ Pattern Output
When you run the program with rows = 5:
*****
****
***
**
*Complete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
for ($i = $rows; $i >= 1; $i--) {
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
echo "*";
}
echo PHP_EOL;
}🧠 How It Works
Setup
$rows is the height. for ($i = $rows; $i >= 1; $i--) starts with the widest row ($i == $rows) and ends at one star.
Padding: echo " "
for ($j = 1; $j <= $rows - $i; $j++) prints $rows - $i spaces. On the first row that count is zero; it grows as $i shrinks.
Stars: echo "*"
for ($k = 1; $k <= $i; $k++) prints $i stars after the padding.
New line
echo PHP_EOL; ends each row. Characters before the newline: ($rows - $i) + $i = $rows every time.
Inverted right-aligned triangle
Star total n(n+1)/2; O(n²) output for n = $rows, O(1) extra space. Wide rows scroll horizontally in the green preview on phones.
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 = $rows; $i >= 1; $i--) {
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
echo "*";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 3 to see how reversing the outer loop changes the shape
- Print a centered inverted pyramid by switching to odd stars + more spaces
- Print a hollow version (stars only on the borders)
- Use a different character (like
#) - Validate that
$rows > 0
Avoid
- Forgetting that spaces increase as stars decrease (alignment breaks)
- Off-by-one errors in the space loop (
$rows - $i) - Mixing tabs and spaces (output alignment changes)
- Skipping newline after each row
- Assuming input is valid without checking
Key Takeaways
Inverted right-aligned = print ($rows - $i) spaces, then $i stars, with $i decreasing.
The outer loop runs backward ($rows to 1) to shrink the star count each row.
Spaces increase by 1 each row, keeping the right edge aligned.
Time complexity is O(n²) for n rows.
This pattern is a stepping stone to centered inverted pyramids and diamond shapes.
❓ Frequently Asked Questions
1 to $rows (Program 3). The space loop stays $rows - $i, but stars become $i as $i increases.Next: Pyramid Pattern
Continue to Program 5 to print a centered pyramid star pattern in PHP.
Right-aligned patterns are excellent practice before moving to centered pyramids, because both require printing spaces and stars with the correct counts.
12 people found this page helpful
