Fixed Start Descending Number Pattern in PHP

What You’ll Learn
How to print a fixed start descending number pattern in PHP using nested for loops. Each row always starts from $n and counts down, but the row gets shorter on each line.
This pattern is a simple way to practice controlling the end condition of the inner loop based on the outer loop variable.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
54321
5432
543
54
5Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $n; $j >= $i; $j--) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the starting digit (printed first on every row).
Outer loop (row index)
for ($i = 1; $i <= $n; $i++) controls how many digits are removed from the end on each next row.
Inner loop (print $n..$i)
for ($j = $n; $j >= $i; $j--) always starts at $n, counts down, and stops at the current row index $i.
New line
echo PHP_EOL; ends the row and moves to the next line.
Fixed-start descending pattern
You print n + (n-1) + ... + 1 digits total, which is n(n+1)/2 — 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 = 1; $i <= $n; $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 . " ";) - Flip the direction to print ascending patterns (start from 1 and count up)
- Right-align the pattern by printing leading spaces before each row
- Try the same logic using letters instead of digits
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing up which variable controls the row length
- Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop increases the row index $i from 1 to $n.
The inner loop always starts at $n and stops at $i, making rows shorter each time.
Total printed digits are triangular: n(n+1)/2, so complexity is O(n²).
This technique is useful for inverted patterns where the starting point stays constant.
❓ Frequently Asked Questions
$j = $n. Only the stop value changes (it stops at $i), so the first digit stays constant.$n to the size you want. For example, $n = 7 prints 7654321, then 765432, down to 7.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 5
Continue to Program 5 to practice another number pattern using nested loops in PHP.
By keeping the start fixed at $n, you can generate many “trim from the end” patterns just by changing the inner loop’s stop condition.
12 people found this page helpful
