Right-Aligned Descending Number Triangle in PHP

What You’ll Learn
How to print a right-aligned descending number triangle in PHP:
1, 21, 321, 4321, 54321.
The alignment comes from printing spaces first and numbers only when the column index is within the current row width.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1
21
321
4321
54321Complete PHP Program
We count down from $n to 1. If $j > $i, we print spaces; otherwise we print $j.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $n; $j >= 1; $j--) {
if ($j > $i) {
echo " ";
} else {
echo $j;
}
}
echo PHP_EOL;
}🧠 How It Works
Set n
$n = 5; sets the width and the number of rows.
Outer loop (row size)
$i increases from 1 to n, so each row prints one more digit than the previous.
Inner loop (descending columns)
The inner loop counts down from $n to 1, which naturally yields the row digits in descending order.
Spaces vs digits
When $j > $i we print spaces; when $j <= $i we print the digit $j.
Right-aligned triangle
Indentation shrinks each row, so the triangle stays aligned to the right edge.
Variation — User Input (CLI) Version
Let the user decide the value of $n at runtime (run from terminal with php):
<?php
echo "Enter n (e.g., 5): ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $n; $j >= 1; $j--) {
echo ($j > $i) ? " " : $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Center-align the triangle by printing leading spaces based on row width
- Add spaces between digits and adjust indentation accordingly
- Print the ascending version by looping j from 1..i
- Use
printfpadding for multi-digit alignment when n is large - Replace digits with characters to generate symbol triangles
Avoid
- Using inconsistent indentation widths (it breaks the alignment)
- Forgetting the newline after each row
- Mixing row/column logic in nested loops
- Skipping input validation in CLI mode
Key Takeaways
The inner loop counts down from $n to 1 to print descending digits.
Spaces are printed when the column index is outside the current row.
As the row grows, indentation shrinks, creating right alignment.
Generalize easily by changing n or reading it from input.
❓ Frequently Asked Questions
$j <= $i.$j = $i down to 1 and print directly without leading spaces.Explore More PHP Number Patterns!
Right-aligned patterns help you understand spacing logic—use it to build pyramids and diamonds next.
Alignment in patterns is often just counting spaces. Once you control whitespace, you can design nearly any triangle, pyramid, or diamond.
12 people found this page helpful
