Descending Repeated Number Pattern in PHP

What You’ll Learn
How to print a descending repeated number pattern in PHP using nested for loops. The digit decreases each row, but the row length increases.
This is a helpful exercise to understand how changing a loop boundary affects repetition.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
5
44
333
2222
11111Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
for ($j = $n; $j >= $i; $j--) {
echo $i;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the starting digit.
Outer loop (digit decreases)
for ($i = $n; $i >= 1; $i--) sets the digit to print on each row (5, 4, 3, 2, 1).
Inner loop (repeat count grows)
for ($j = $n; $j >= $i; $j--) controls how many times echo $i; runs. As $i decreases, the loop runs more times.
New line
echo PHP_EOL; ends the row and moves to the next line.
Descending repeated pattern
Total printed digits grow like a triangular number, so the time complexity is O(n²).
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 = $n; $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 . " ";) - Swap the inner loop bounds to change the repetition rule
- Print stars instead of digits to build star patterns
- Try formatting output for HTML by using
<br>instead ofPHP_EOL
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Printing
$jby mistake (this pattern prints$i) - Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop chooses the digit to print on each row.
The inner loop controls how many times the digit repeats.
Total prints are triangular, so runtime is O(n²).
Small loop-bound changes can create many different repeated-digit patterns.
❓ Frequently Asked Questions
$i = 3, the inner loop runs 3 times and prints $i each time.$n to the maximum starting digit you want. The last row will print 1 repeated $n times.echo $i . " "; instead of echo $i;.Next: PHP Number Pattern 11
Continue to Program 11 to print a shrinking repeated-digit triangle in PHP.
This is a neat example where the value and the count move in opposite directions—great practice for reasoning about nested loops.
12 people found this page helpful
