Increasing Odd-Length Number Pattern in PHP

What You’ll Learn
How to print an increasing odd-length number pattern in PHP:
1, 123, 12345, 1234567, 123456789.
The trick is to increase the row limit by 2 each time, so the number of digits per row stays odd.
⭐ Pattern Output
For a maximum width of 9, the pattern looks like this:
1
123
12345
1234567
123456789Complete PHP Program
The outer loop picks the row width (1, 3, 5, 7, 9). The inner loop prints numbers from 1 to that width.
<?php
$max = 9;
for ($i = 1; $i <= $max; $i += 2) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Set the maximum width
$max = 9; sets the last row length (odd).
Outer loop (odd row lengths)
for ($i = 1; $i <= $max; $i += 2) produces widths 1, 3, 5, 7, 9.
Inner loop (print 1..i)
for ($j = 1; $j <= $i; $j++) prints digits from 1 to the current row width.
New line
echo PHP_EOL; moves to the next row.
Odd-length growth
The row length grows by 2 each time, so it stays odd and reaches 9 on the last row.
Variation — User Input (CLI) Version
Let the user choose the maximum odd width (run from terminal with php):
<?php
echo "Enter the maximum width (odd number): ";
$max = (int) trim(fgets(STDIN));
if ($max < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
if ($max % 2 === 0) {
$max -= 1; // keep widths odd: 1,3,5,...
}
for ($i = 1; $i <= $max; $i += 2) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for readability (
echo $j . " ";) - Print the descending variant by looping
$jfrom$idown to 1 - Start from 0 by printing
$j - 1or adjusting the loop - Right-align the pattern by printing leading spaces
- Use a different sequence (even numbers, odds only, etc.) inside the inner loop
Avoid
- Using an even max width without adjusting (you’ll get an extra even-length row)
- Forgetting the newline after each row
- Mixing up row/column logic (outer loop = row width)
- Skipping input validation in CLI mode
Key Takeaways
The outer loop increases by 2 to generate odd row lengths.
The inner loop prints 1 through the current row limit.
Setting $max controls the final row width.
Step-size loops are a handy technique for selecting only odd or even counts.
❓ Frequently Asked Questions
$i += 2, so row widths increase by 2 each time.$i++) so each row length grows by one instead of two.echo $j . " "; inside the inner loop.Explore More PHP Number Patterns!
Odd-length patterns are a great stepping stone to pyramids, diamonds, and centered patterns.
Increasing by 2 is the simplest way to iterate over odd counts (or odd numbers). The same trick works for evens by starting at 2.
12 people found this page helpful
