Centered Odd-Row Continuous Numbers in PHP

What You’ll Learn
How to print a centered continuous number pattern in PHP with odd row widths:
1, 2 3 4, 5 6 7 8 9
We print leading spaces for alignment, then print numbers using an incrementing counter.
⭐ Pattern Output
The pattern looks like this:
1
2 3 4
5 6 7 8 9Complete PHP Program
We print spaces first, then print numbers while increasing $k.
<?php
$k = 1;
for ($i = 1; $i <= 5; $i += 2) {
for ($j = 5; $j >= 1; $j--) {
if ($j > $i) {
echo " ";
} else {
echo $k++ . " ";
}
}
echo PHP_EOL;
}🧠 How It Works
Initialize a counter
$k = 1; stores the next number to print.
Outer loop (odd row widths)
for ($i = 1; $i <= 5; $i += 2) uses widths 1, 3, 5.
Print spaces for centering
When $j > $i, we print spaces to indent the row.
Print and increment numbers
When $j <= $i, we print $k and then increment it with $k++.
Centered odd-row pattern
Rows grow by 2 each time and numbers continue from where the previous row ended.
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, e.g., 5): ";
$max = (int) trim(fgets(STDIN));
if ($max < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
if ($max % 2 === 0) {
$max -= 1;
}
$k = 1;
for ($i = 1; $i <= $max; $i += 2) {
for ($j = $max; $j >= 1; $j--) {
if ($j > $i) {
echo " ";
} else {
echo $k++ . " ";
}
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use padding (like
printf("%2d ", $k++)) for aligned columns - Increase the max width to generate a bigger triangle (7, 9, ...)
- Change the counter start value (start from 10, 100, ...)
- Replace spaces with dots to visualize alignment while learning
- Convert to a centered pyramid by printing fixed row lengths
Avoid
- Mixing up the spacing logic (indent must happen before numbers)
- Resetting the counter inside the outer loop
- Skipping input validation in the CLI version
- Assuming single-digit numbers for alignment
Key Takeaways
Use a counter to keep numbers continuous across rows.
Row widths are odd because the outer loop steps by 2.
Leading spaces create the centered look.
Formatting/padding becomes important for multi-digit counters.
❓ Frequently Asked Questions
$k++ every time we print a number, and we never reset $k inside the loops.Explore More PHP Number Patterns!
Once you’re comfortable with spacing logic, try centered pyramids and diamonds.
Centering output is usually just a matter of printing the right number of spaces. Many pattern problems become easy once you separate indentation from content.
12 people found this page helpful
