Bidirectional Number Triangle in PHP

What You’ll Learn
How to print a repeating-number decreasing triangle in PHP:
11111, 2222, 333, 22, 1.
We use a decreasing inner loop for row length and a small conditional to mirror values on the last rows.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
11111
2222
333
22
1Complete PHP Program
The inner loop controls row length; the printed digit depends on whether we are in the first half or mirrored half.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
if ($i < 4) {
echo $i;
} else {
echo 6 - $i;
}
}
echo PHP_EOL;
}🧠 How It Works
Choose n
$n = 5; controls the triangle height and first row width.
Outer loop (rows)
for ($i = 1; $i <= $n; $i++) increments the row number.
Inner loop (decreasing width)
for ($j = $i; $j <= $n; $j++) prints fewer characters each row as $i increases.
Choose which digit to print
We print $i for rows 1..3, then mirror using 6 - $i for rows 4..5 to produce 2 and 1.
Repeating decreasing triangle
Row width decreases by one each line, creating a compact triangle.
Variation — User Input (CLI) Version
Let the user choose the number of rows (run from terminal with php):
<?php
echo "Enter the number of rows: ";
$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 = $i; $j <= $n; $j++) {
$val = ($i <= (int) ceil($n / 2)) ? $i : (($n + 1) - $i);
echo $val;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Replace the digit with a character to create symbol triangles
- Print spaces between digits for larger
$nvalues - Use a single formula for the value (as shown in the CLI version)
- Mirror horizontally by padding with spaces on the left
- Convert it into an increasing triangle by changing the inner loop bounds
Avoid
- Hardcoding the mirroring constants if you plan to scale
$n - Forgetting that the inner loop controls the decreasing width
- Skipping validation for CLI input
- Assuming the pattern is symmetric for any n (check even n behavior)
Key Takeaways
The inner loop prints from $i to $n, shrinking each row.
The printed digit can be computed from the row index.
For fixed n=5, the mirror shortcut 6 - $i works for the last rows.
Generalize by deriving the mirrored value from $n instead of hardcoding.
❓ Frequently Asked Questions
$j = $i and runs to $n, so each next row prints one fewer value.6 - $i.Explore More PHP Number Patterns!
Repeating-number triangles are perfect practice for nested loops and conditional logic.
Many pattern problems can be simplified by finding a formula for the printed value per row—once you have that, the rest is just loop bounds.
12 people found this page helpful
