Growing Suffix Number Pattern in PHP

What You’ll Learn
How to print a growing suffix number pattern in PHP using nested for loops. Each row prints from a decreasing start value up to $n.
This teaches you how to make the inner loop start depend on the outer loop.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
5
45
345
2345
12345Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
for ($j = $i; $j <= $n; $j++) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the last digit printed on every row.
Outer loop (start value decreases)
for ($i = $n; $i >= 1; $i--) controls the first digit on each row: 5, then 4, then 3, ...
Inner loop (print $i..$n)
for ($j = $i; $j <= $n; $j++) prints digits from the row start $i up to $n.
New line
echo PHP_EOL; ends the row and moves to the next line.
Growing suffix pattern
Total printed digits are triangular: 1+2+…+n = 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 = $n; $i >= 1; $i--) {
for ($j = $i; $j <= $n; $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 suffix” by reversing the loop directions
- Right-align the pattern with leading spaces
- Use the same idea for alphabet suffix patterns
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing up loop directions (outer loop desc, inner loop asc here)
- Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop chooses the starting digit by counting down from $n to 1.
The inner loop prints from $i up to $n for each row.
Total printed digits still follow n(n+1)/2, so time complexity is O(n²).
This is a classic example of making the inner loop start value depend on the outer loop variable.
❓ Frequently Asked Questions
$i = $n. The inner loop then runs from $j = $i to $n, so when $i = $n, only one number is printed.$n to the size you want. For example, $n = 7 prints 7, 67, 567, ... up to 1234567.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 7
Continue to Program 7 to practice another number pattern using nested loops in PHP.
This pattern is the “mirror” of an incrementing-start pattern: instead of starting each row at 1 or 2, you start at the row index and extend to the same end value each time.
12 people found this page helpful
