Reverse Descending Number Triangle in PHP

What You’ll Learn
How to print a reverse descending number triangle in PHP using nested for loops. Each row starts from the current row limit and counts down to 1.
This pattern strengthens your understanding of descending loops and how the inner loop length depends on the outer loop value.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
54321
4321
321
21
1Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the triangle height and the largest digit printed.
Outer loop (descending rows)
for ($i = $n; $i >= 1; $i--) controls how many digits appear on each row by decreasing the row limit.
Inner loop (print $i..1)
for ($j = $i; $j >= 1; $j--) prints digits from the row limit down to 1 using echo $j;.
New line
echo PHP_EOL; ends the row and moves to the next line.
Reverse descending triangle
Total printed digits are still triangular: 1+2+…+n = n(n+1)/2, so the time complexity is O(n²).
Variation — User Input (CLI) Version
Let the user decide $n at runtime (run from terminal with php):
<?php
echo "Enter the value of n: ";
$n = (int) trim(fgets(STDIN));
for ($i = $n; $i >= 1; $i--) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$n < 1) before printing - Add spaces between numbers (for example,
echo $j . " ";) - Print the increasing version by counting
$jup from 1 to$i(Program 1) - Right-align the triangle by printing leading spaces
- Try printing the same idea with letters to build alphabet patterns
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing up loop directions (use
--for descending loops) - Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop decreases the row length by counting down from $n to 1.
The inner loop prints from $i down to 1 on each row.
Total printed digits still follow a triangular count: n(n+1)/2.
This pattern is a good stepping stone for inverted pyramids and mirrored patterns.
❓ Frequently Asked Questions
$j = $i and decrements until 1, printing $i, $i-1, ... , 1 on the same line.$n to the size you want. For example, $n = 7 prints 7654321, then 654321, down to 1.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 4
Continue to Program 4 to learn another number pattern using nested loops in PHP.
Descending loops are common in pattern problems because they naturally shrink the number of printed digits row by row—perfect for inverted shapes.
12 people found this page helpful
