PHP Decreasing Number Triangle Pattern (Right-Aligned)
Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview
Definition
What Is This Pattern?
A right-aligned decreasing triangle indents each row, then prints values from $rows down to the current $i — so every row starts at the same high number.
1. Same rules. Indent $i - 1 times; print $rows down to $i.
2. Full width. The last row has no indentation — just 3 2 1.
Edge Cases & Pitfalls
Check these before calling the solution done.
skip indent
Omit the indentation loop
Without for ($j = 1; $j < $i; $j++), every row starts at the left margin.
ascending i
Loop $i from 1 up instead of down
The tip and base swap order. Keep for ($i = $rows; $i >= 1; $i--).
no format
Use echo $j without width
Columns drift for multi-digit values. Prefer printf("%2d", $j).
rows = 1
Single 1
Output is just the formatted 1 — no indentation.
rows ≤ 0
Empty output
The outer loop never runs. Validate and prompt again for clearer UX.
Bad input
Unchecked cast
Always check is_numeric before casting so non-numeric input does not silently become 0.
Analysis
Time and Space Complexity
Program
Time
Extra space
Fixed / compact (Examples 1, 3)
O(n²)
O(1)
User input (Example 2)
O(n²)
O(1)
Indent steps plus printed numbers across all rows sum to roughly n² work.
Remember
Key Takeaways
Rule: indent $i - 1 times, then print $rows..$i with width 2.
Outer direction:$i runs from $rows down to 1 so the tip appears first.
echo vs PHP_EOL: indents and numbers stay on the line; echo PHP_EOL advances after both loops.
Next step: Program 37 prints a palindrome number triangle (1, 212, 32123…).
One line: for each $i from $rows down to 1, indent then print the decreasing sequence $rows..$i.
Frequently Asked Questions
A right-aligned decreasing triangle: row 1 prints 5, row 2 prints 5 4, row 3 prints 5 4 3, and so on until 5 4 3 2 1.
An indentation loop prints two spaces while $j < $i before the number loop runs, pushing shorter rows to the right.
The format reserves 2 columns per number (right-aligned), keeping columns stable in the console output.
The number loop runs for ($j = $rows; $j >= $i; $j--), so every row begins at $rows and counts down to the current $i.
Program 35 uses a continuous counter. Program 36 restarts from $rows on each row with a separate indentation loop.
Replace 5 with $rows in the outer loop bound — see Example 2.
O(n²) for n rows because total printed numbers are 1 + 2 + ... + n = n(n+1)/2.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.
Only one row prints — a single number with no leading indentation.
🤔
Did you know?
Each row starts from $rows and counts down to $i. An indentation loop prints two spaces per step ($j = 1..$i-1), then printf("%2d", $j) keeps number columns aligned.