Reverse Ascending Number Triangle in PHP

What You’ll Learn
How to print a reverse ascending number triangle in PHP using nested for loops. The triangle grows each row, but numbers are printed in reverse order on each line.
This pattern is excellent practice for writing a descending inner loop inside an ascending outer loop.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1
21
321
4321
54321Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets how many rows are printed.
Outer loop (triangle grows)
for ($i = 1; $i <= $n; $i++) increases the row length by 1 each time.
Inner loop (print $i..1)
for ($j = $i; $j >= 1; $j--) prints the current row in reverse order, for example 4 prints 4321.
New line
echo PHP_EOL; ends the row and moves to the next line.
Reverse ascending triangle
Total printed digits: 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 = 1; $i <= $n; $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 normal ascending triangle by counting
$jup from 1 to$i - Right-align the triangle by printing leading spaces
- Use the same technique for star or alphabet triangles
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing up loop directions (inner loop desc here)
- Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop grows the triangle from 1 row up to $n rows.
The inner loop prints the row in reverse: from $i down to 1.
Total printed digits follow n(n+1)/2, so complexity is O(n²).
This pattern is great practice for combining ascending and descending loops together.
❓ Frequently Asked Questions
$i = 4, the inner loop starts at $j = 4 and decrements down to 1, printing 4, 3, 2, 1.$n to the number of rows you want. For example, $n = 7 prints down to 7654321 on the last row.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 8
Continue to Program 8 to practice another number pattern using nested loops in PHP.
Patterns like this help you get comfortable switching loop directions. Many interview problems rely on the same idea: one loop grows while another counts down.
12 people found this page helpful
