Right-Aligned Decreasing Triangle in PHP

What You’ll Learn
How to print a right-aligned decreasing number triangle in PHP. Each row begins at 5 and counts down to the row limit.
This pattern is excellent practice for combining alignment logic (spaces) with reverse loops (counting down).
⭐ Pattern Output
For $start = 5, the pattern looks like this:
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1Complete PHP Program
We print leading spaces for right alignment, then print numbers from $start down to the row limit.
<?php
$start = 5;
for ($i = $start; $i >= 1; $i--) {
for ($s = 1; $s < $i; $s++) {
echo " ";
}
for ($j = $start; $j >= $i; $j--) {
echo $j . " ";
}
echo PHP_EOL;
}🧠 How It Works
Set the starting number
$start = 5; decides the top value and total rows.
Outer loop (row limit decreases)
for ($i = $start; $i >= 1; $i--) sets the minimum value printed on each row.
Print leading spaces
for ($s = 1; $s < $i; $s++) prints blanks so early rows appear shifted to the right.
Print numbers from $start down to $i
for ($j = $start; $j >= $i; $j--) prints the decreasing sequence on the current row.
Right-aligned decreasing triangle
Total printed values are 1+2+…+n = n(n+1)/2, so runtime is O(n²).
Variation — User Input (CLI) Version
Let the user decide the starting number at runtime using standard input (run from terminal with php):
<?php
echo "Enter the starting number: ";
$start = (int) trim(fgets(STDIN));
if ($start < 1) {
exit("Starting number must be at least 1." . PHP_EOL);
}
for ($i = $start; $i >= 1; $i--) {
for ($s = 1; $s < $i; $s++) {
echo " ";
}
for ($j = $start; $j >= $i; $j--) {
echo $j . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use fixed-width formatting (like
str_pad()) to align multi-digit numbers - Replace spaces with tabs or
if printing in HTML - Change the start value to generate bigger triangles
- Mirror the triangle to create a diamond-like pattern
- Print commas instead of spaces for CSV-style output
Avoid
- Using negative or zero start values without validation
- Forgetting the newline after each row (
PHP_EOL) - Mixing row and column responsibilities (outer loop = rows, inner loops = spaces/numbers)
- Assuming user input is always valid
Key Takeaways
The triangle is right-aligned by printing leading spaces on each row.
Row $i prints the values $start, $start-1, ..., $i.
Total printed numbers are n(n+1)/2, so runtime is O(n²).
The same logic can be used to create other right-aligned increasing/decreasing patterns.
❓ Frequently Asked Questions
$i = $start, the loop prints from $start down to $i, which is just one value.str_pad().<br> instead of PHP_EOL and consider printing for spaces, or use CSS grid for perfect alignment.Explore More PHP Number Patterns!
Practice alignment and reverse loops with more number patterns.
This pattern is essentially a right-aligned triangle where each row prints a suffix of the sequence 5 4 3 2 1.
12 people found this page helpful
