Odd-Step Descending Number Pattern in PHP

What You’ll Learn
How to print an odd-step descending number pattern in PHP using nested for loops. The first row prints 1 through a starting width (like 7), then each next row prints two fewer numbers.
This pattern is useful for practicing how the outer loop controls row length and how the inner loop controls what appears in each row.
⭐ Pattern Output
For a starting width of 7, the pattern looks like this:
1234567
12345
123
1Complete PHP Program
The outer loop reduces the row width by 2. The inner loop prints numbers from 1 to the current row width.
<?php
$start = 7;
for ($i = $start; $i >= 1; $i -= 2) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Pick the starting width
$start = 7; sets the first row length.
Outer loop (shrink by 2)
for ($i = $start; $i >= 1; $i -= 2) produces widths 7, 5, 3, 1 by subtracting 2 each row.
Inner loop (print 1..$i)
for ($j = 1; $j <= $i; $j++) prints digits from 1 up to the current width $i using echo $j;.
Move to the next line
echo PHP_EOL; prints a newline after each row.
Odd-step descending rows
Row lengths are odd numbers that decrease by 2: 7, 5, 3, 1. This is a compact way to practice nested loops and step sizes.
Variation — User Input (CLI) Version
Let the user choose the starting width at runtime using standard input (run from terminal with php):
<?php
echo "Enter the starting width (odd number): ";
$start = (int) trim(fgets(STDIN));
if ($start < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
if ($start % 2 === 0) {
$start -= 1; // make it odd for a clean ... 5,3,1 ending
}
for ($i = $start; $i >= 1; $i -= 2) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Change
$startto print larger or smaller patterns (9, 11, ...) - Add spaces between numbers (for example,
echo $j . " ";) - Right-align the pattern by printing leading spaces on each row
- Replace numbers with characters to create alphabet patterns
- Validate input to ensure
$startis positive
Avoid
- Using an even start without adjusting (you’ll end with
... 2instead of... 1) - Forgetting the newline after each row
- Mixing up row/column logic (keep the outer loop for row widths)
- Assuming user input is always valid in CLI mode
Key Takeaways
❓ Frequently Asked Questions
2 each time ($i -= 2), so the number of printed digits shrinks by two per row.$start to any positive odd number. The rows will be $start, $start-2, $start-4, ... down to 1.echo $j . " ";. That makes the output easier to read for bigger widths.n + (n-2) + (n-4) + ... + 1 digits overall.Explore More PHP Number Patterns!
Practice nested loops with patterns that change width, steps, alignment, and symmetry.
If you start from an odd width n, the total numbers printed are n + (n-2) + (n-4) + ... + 1, which equals \(((n+1)/2)^2\). For n = 7, that’s 16 digits.
12 people found this page helpful
