Shrinking Repeated Number Pattern in PHP

What You’ll Learn
How to print a shrinking repeated number pattern in PHP using nested for loops. Each row prints the same digit multiple times, but the repetition count decreases by 1 on each next row.
This pattern teaches you how to set the inner loop length using a variable start point.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
11111
2222
333
44
5Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
echo $i;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; defines how many rows to print and the maximum repetition count.
Outer loop (digit increases)
for ($i = 1; $i <= $n; $i++) selects which digit to print on the row.
Inner loop (repeat count shrinks)
for ($j = $i; $j <= $n; $j++) runs ($n - $i + 1) times, so the number repeats fewer times on each next row.
New line
echo PHP_EOL; ends the row and moves to the next line.
Shrinking repeated pattern
The total printed digits are still triangular, so runtime 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 = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $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 digit direction (count down) to create inverted variants
- Print a constant digit (like 1) to build
11111,1111,111... - Try printing stars instead of digits for star patterns
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 to print on each row.
The inner loop runs from $i to $n, controlling how many times the digit repeats.
Total printed digits are triangular, so runtime is O(n²).
This pattern is great practice for thinking in terms of “range length” ($n - $i + 1).
❓ Frequently Asked Questions
$i = $n, the inner loop runs only once (from $j = $n to $n), so the digit prints once.$n to the number of rows you want. The first row prints 1 repeated $n times, and the last row prints $n once.echo $i . " "; instead of echo $i;.Next: PHP Number Pattern 13
Continue to Program 13 to print an alternating ascending/descending pattern using an if condition.
Patterns like this are a good way to learn how changing the inner loop start value changes the row length without needing extra variables.
12 people found this page helpful
