Growing Prefix Descending Number Pattern in PHP

What You’ll Learn
How to print a growing prefix descending number pattern in PHP using nested for loops. The first row prints the last number only, and each next row adds the next descending digit.
This pattern is a good way to practice descending inner loops where the stop condition depends on the outer loop.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
5
54
543
5432
54321Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
for ($j = $n; $j >= $i; $j--) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the largest digit printed on every row.
Outer loop (grow row length)
for ($i = $n; $i >= 1; $i--) decreases $i, which causes the inner loop to run more times each next row.
Inner loop (print $n..$i)
for ($j = $n; $j >= $i; $j--) prints a descending sequence starting at $n and stopping at $i.
New line
echo PHP_EOL; ends the row and moves to the next line.
Growing prefix pattern
Total printed digits still form a triangular count, 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 $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$n < 1) before printing - Add spaces between numbers (for example,
echo $j . " ";) - Print the shrinking version by reversing the outer loop direction
- Right-align the triangle by printing leading spaces
- Try the same pattern with letters to create alphabet sequences
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing up the loop directions (both loops descend here)
- Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop controls how many digits are printed per row by changing the stop value.
The inner loop prints from $n down to $i on each row.
Total printed digits grow like a triangular number, so time is O(n²).
This is a useful building block for many reversed and mirrored patterns.
❓ Frequently Asked Questions
$i = $n. The inner loop then prints from $j = $n down to $i, which is only one digit when $i = $n.$n to the size you want. For example, $n = 7 prints 7, then 76, then 765, up to 7654321.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 9
Continue to Program 9 to learn a repeated-digit number pattern in PHP.
Patterns like this are great practice for controlling loop boundaries. Small changes to the inner loop range can create completely different pattern families.
12 people found this page helpful
