Shrinking Repeated Number Triangle in PHP

What You’ll Learn
How to print a shrinking repeated number triangle in PHP using nested for loops. Each row prints the same digit multiple times, and both the digit and repetition count decrease each row.
This pattern is a common practice problem for understanding how to shrink output using loop boundaries.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
55555
4444
333
22
1Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
for ($j = 1; $j <= $i; $j++) {
echo $i;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the starting digit and the maximum row width.
Outer loop (digit decreases)
for ($i = $n; $i >= 1; $i--) chooses which digit to print on the row (5, 4, 3, 2, 1).
Inner loop (repeat $i times)
for ($j = 1; $j <= $i; $j++) prints echo $i; exactly $i times, so the row shrinks as $i shrinks.
New line
echo PHP_EOL; ends the row and moves to the next line.
Shrinking repeated triangle
Total prints are triangular, so the time complexity is O(n²) for n rows.
Variation — User Input (CLI) Version
Let the user decide $n at runtime (run from terminal with php):
<?php
echo "Enter the value of n: ";
$n = (int) trim(fgets(STDIN));
for ($i = $n; $i >= 1; $i--) {
for ($j = 1; $j <= $i; $j++) {
echo $i;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$n < 1) before printing - Add spaces between digits (for example,
echo $i . " ";) - Reverse the outer loop direction to build a growing repeated-digit triangle
- Use the same idea to print characters instead of digits
- Try printing into a string per row before echoing for more control
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Printing
$jinstead of$i(this pattern repeats the row digit) - Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop selects the digit for each row (from $n down to 1).
The inner loop repeats the digit exactly $i times.
Total prints are triangular, so runtime is O(n²).
This pattern is a great building block for inverted repeated-digit triangles.
❓ Frequently Asked Questions
$i = 5, the inner loop runs 5 times and prints $i each time.$n to the size you want. The first row prints $n repeated $n times, and the last row prints 1.echo $i . " "; instead of echo $i;.Next: PHP Number Pattern 12
Continue to Program 12 to learn another number pattern in PHP.
Many “triangle” patterns are just different ways of deciding what to print (value) and how many times to print it (count).
12 people found this page helpful
