Alternating Ascending/Descending Number Pattern in PHP

What You’ll Learn
How to print an alternating ascending/descending number pattern in PHP. Odd-length rows print numbers from 1 to $i, and even-length rows print from $i down to 1.
This pattern is great for practicing nested loops along with conditional logic using if/else.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
12345
4321
123
21
1Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = $n; $i >= 1; $i--) {
if ($i % 2 === 0) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
} else {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the largest row length.
Outer loop (row length decreases)
for ($i = $n; $i >= 1; $i--) controls the current row length.
If/else decides direction
When $i is even, print descending with for ($j = $i; $j >= 1; $j--). When $i is odd, print ascending with for ($j = 1; $j <= $i; $j++).
New line
echo PHP_EOL; ends each row.
Alternating direction pattern
You still print about n(n+1)/2 digits total, 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 = $n; $i >= 1; $i--) {
if ($i % 2 === 0) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
} else {
for ($j = 1; $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 readability
- Alternate based on row index rather than
$iparity - Invert the condition to swap which rows print ascending/descending
- Try alternating two different patterns (numbers vs stars)
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validation
- Mixing up loop directions inside the if/else
- Hard-coding 5 instead of using
$n
Key Takeaways
if/else can switch between two different inner-loop directions.
Odd rows can print ascending (1..i) while even rows print descending (i..1).
Total prints stay triangular, so runtime is O(n²).
This pattern is a stepping stone for zig-zag and wave-style outputs.
❓ Frequently Asked Questions
4 down to 1.$n to the maximum row length you want. The program prints rows from $n down to 1.$row and alternate when $row % 2 === 0.Next: PHP Number Pattern 14
Continue to Program 14 for the next number pattern exercise in PHP.
Adding a single if can dramatically increase the variety of patterns you can generate—great for practicing clean control flow.
12 people found this page helpful
