Number Pattern 39 in PHP

What You’ll Learn
How to print Number Pattern 39 in PHP using nested loops. Each row is made of two parts: an ascending sequence from $i to $n, followed by a descending sequence from $i-1 to 1.
This creates rows like 23451 and 45321.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
12345
23451
34521
45321
54321Complete PHP Program
First print $i..$n, then print $i-1..1 to complete the row.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
echo $j;
}
for ($k = $i; $k > 1; $k--) {
echo $k - 1;
}
echo PHP_EOL;
}🧠 How It Works
Choose the maximum number
$n = 5; defines the range of digits and the number of rows.
Outer loop (rows)
for ($i = 1; $i <= $n; $i++) controls the starting digit for each row.
First half: print $i..$n
for ($j = $i; $j <= $n; $j++) prints ascending digits from the row start.
Second half: print $i-1..1
for ($k = $i; $k > 1; $k--) prints the wrap-around tail to complete the row.
Two-part row construction
Each row prints exactly n digits, and over n rows that leads to O(n²) work.
Variation — User Input (CLI) Version
Let the user decide $n at runtime using standard input (run from terminal with php):
<?php
echo "Enter n: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
exit("n must be at least 1." . PHP_EOL);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
echo $j;
}
for ($k = $i; $k > 1; $k--) {
echo $k - 1;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Replace digits with letters to generate a similar alphabet pattern
- Add spaces between digits for readability (for example, print
$j . " ") - Generate the same row using arrays, then join and print once
- Start from a different base by changing the outer loop range
- Reverse the output order (print rows from
$ndown to 1)
Avoid
- Using invalid
$nwithout input validation - Mixing row/column logic (outer loop should control rows)
- Assuming output stays identical if you add separators
- Forgetting the newline after each row
Key Takeaways
Each row is built from two runs: $i..$n then $i-1..1.
Every row prints exactly $n digits.
The pattern scales by changing only $n.
Total work is O(n²).
❓ Frequently Asked Questions
$i=3, the first loop prints 345. The second loop prints 21. Combined, the row is 34521.$n back to 1.echo $j . " ";. The pattern remains the same, but the formatting changes.n digits for each of n rows.Explore More PHP Number Patterns!
Try more rotation and wrap-around patterns to strengthen your loop thinking.
Each row contains all numbers from 1 to $n exactly once—just in a different order.
12 people found this page helpful
