Right-Aligned Number Triangle in PHP

What You’ll Learn
How to print a right-aligned number triangle in PHP where numbers increase continuously (1, 2, 3, …) across rows.
You’ll use a counter variable and nested loops to print spaces on the left and numbers on the right.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15Complete PHP Program
We print blanks for alignment, then print numbers using a counter $k that increments after each print.
<?php
$rows = 5;
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
// leading blanks (as spaces) for right alignment
for ($s = $rows - $i; $s >= 1; $s--) {
echo " ";
}
for ($j = 1; $j <= $i; $j++) {
echo $k++ . " ";
}
echo PHP_EOL;
}🧠 How It Works
Initialize rows and counter
$rows = 5; sets the height and $k = 1; starts the sequence.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) prints one row at a time.
Print leading spaces
The loop from $rows - $i down to 1 prints blanks so the numbers shift to the right.
Print sequential numbers
The inner loop runs $j = 1..$i and prints $k++ each time.
Right-aligned triangle
Total printed numbers are 1+2+…+n = n(n+1)/2, so runtime is O(n²).
Variation — User Input (CLI) Version
Let the user decide the number of rows at runtime using standard input (run from terminal with php):
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
exit("Rows must be at least 1." . PHP_EOL);
}
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
for ($s = $rows - $i; $s >= 1; $s--) {
echo " ";
}
for ($j = 1; $j <= $i; $j++) {
echo $k++ . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Format spacing using
str_pad()to align multi-digit numbers (10, 11, 12, ...) - Reset the counter each row to print repeated sequences per line
- Convert it into a centered pyramid by doubling the left padding
- Print the same triangle in reverse (descending) order
- Use HTML output with CSS grid when rendering on a webpage
Avoid
- Forgetting to reset
$kwhen you want a fresh sequence for a new run - Using raw spaces for large patterns with multi-digit numbers (alignment will drift)
- Mixing row and column responsibilities (outer loop = rows, inner loops = spaces/numbers)
- Skipping input validation in the CLI version
Key Takeaways
A counter ($k) prints a continuous sequence across rows.
Leading spaces right-align the triangle (spaces = $rows - $i).
Row $i prints $i numbers, so total prints are n(n+1)/2.
Runtime grows as O(n²) with the number of rows.
❓ Frequently Asked Questions
10 takes two characters while 9 takes one. Use fixed-width formatting (like str_pad()) to keep columns aligned.PHP_EOL with <br> and use for spacing, or render with HTML/CSS (grid/flex) for better alignment.Explore More PHP Number Patterns!
From simple triangles to advanced alignments—keep practicing nested loops.
The count of numbers printed after n rows is a triangular number: 1+2+…+n = n(n+1)/2. For 5 rows, that’s 15.
12 people found this page helpful
