Inverted Right-Angled Triangle Star Pattern in PHP

What You'll Learn
This program prints an inverted right-angled triangle where each next row contains one less star than the previous row.
Row i prints exactly i stars while i decreases from rows to 1.
⭐ 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 <= $i; $j++) {
echo "*";
}
echo PHP_EOL;
}🧠 How It Works
Setup
$rows sets the first line width. for ($i = $rows; $i >= 1; $i--) counts down so the widest row prints first.
Stars: echo "*"
for ($j = 1; $j <= $i; $j++) prints $i asterisks on one line.
New line
echo PHP_EOL; ends the row before $i changes. Variation: echo str_repeat("*", $i) . PHP_EOL;.
Inverted triangle
Total stars still n(n+1)/2 — O(n²) time, O(1) extra space. The widest line scrolls horizontally in the green preview on small screens.
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 <= $i; $j++) {
echo "*";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print Program 1 (upright triangle) to compare both shapes
- Validate that
$rows > 0before printing - Use
str_repeat("*", $i)to print each row without an inner loop - Add spaces between stars for visual variety
- Create a hollow inverted triangle (print only border stars)
Avoid
- Forgetting the newline after each row
- Assuming CLI input is always valid
- Mixing HTML output with CLI output in the same script without intent
- Off-by-one errors in loop bounds (
>= 1matters) - Over-complicating a simple pattern (keep it readable)
Key Takeaways
Outer loop starts from rows and goes down to 1, so the triangle shrinks each row.
Row i prints exactly i stars, so the widest row comes first.
Total stars are n(n + 1)/2, so time complexity is O(n²).
This is the mirror of Program 1 and helps you practice decrementing loops.
For CLI programs, fgets(STDIN) is a simple way to read input.
❓ Frequently Asked Questions
$i = $rows down to 1. For each row $i, the inner loop runs from $j = 1 to $i, printing one star per iteration. So the first row prints $rows stars and each next row prints one less.$i, you can print str_repeat("*", $i). This often makes the code shorter and easier to read.$_GET or $_POST. For example: $rows = (int)($_GET["rows"] ?? 5);. This tutorial uses CLI input because it matches common pattern-printing exercises.Next: Right-Aligned Triangle
Continue to Program 3 to print the right-aligned star triangle pattern in PHP.
This is the mirror of Program 1. Practicing both helps you master loop bounds and makes it easier to build larger patterns like pyramids and diamonds.
12 people found this page helpful
