0-Centered Mirror Numbers in PHP

What You’ll Learn
How to print a 0-centered mirror number pattern in PHP where each row mirrors around a central 0.
Example last line: 1234567890987654321.
This pattern is built using two inner loops: one ascending to 9, one descending back to the start, with a fixed 0 in the middle.
⭐ Pattern Output
The pattern looks like this:
0
909
89098
7890987
678909876
56789098765
4567890987654
345678909876543
23456789098765432
1234567890987654321Complete PHP Program
We print digits from $i up to 9, then print 0, then print digits from 9 down to $i.
<?php
for ($i = 10; $i >= 1; $i--) {
for ($j = $i; $j < 10; $j++) {
echo $j;
}
echo "0";
for ($k = 9; $k >= $i; $k--) {
echo $k;
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls the start digit
for ($i = 10; $i >= 1; $i--) sets the leftmost digit of the row (from none down to 1).
Left side: print i..9
for ($j = $i; $j < 10; $j++) prints ascending digits that end at 9.
Center: print 0
echo "0"; places the center digit for symmetry.
Right side: print 9..i
for ($k = 9; $k >= $i; $k--) prints the descending mirror back to the start digit.
0-centered mirroring
Each row is symmetric around 0 because the right side mirrors the left side in reverse.
Variation — User Input (CLI) Version
Let the user choose the maximum digit (run from terminal with php):
<?php
echo "Enter the maximum digit (1-9, e.g., 9): ";
$max = (int) trim(fgets(STDIN));
if ($max < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
if ($max > 9) $max = 9;
for ($i = $max + 1; $i >= 1; $i--) {
for ($j = $i; $j <= $max; $j++) {
echo $j;
}
echo "0";
for ($k = $max; $k >= $i; $k--) {
echo $k;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print spaces between digits to make long lines more readable
- Replace the center
0with another symbol to create new variants - Use padding to align multi-digit output if you increase beyond single digits
- Generate only a subset of rows by limiting the outer loop range
- Convert it into a diamond by adding a second half that shrinks again
Avoid
- Mixing loop bounds (ascending must stop at max, descending must start at max)
- Forgetting the newline after each row
- Skipping input validation for the CLI version
- Assuming the first inner loop always prints at least one number
Key Takeaways
Each row prints an ascending part, a center 0, then a descending mirror.
The start digit changes each row via the outer loop.
Mirroring is achieved by reversing the loop direction for the right side.
Parameterize the max digit to generate smaller or larger versions.
❓ Frequently Asked Questions
0 appears.echo "0"; with any character or number you like.echo $j . " "; and echo $k . " ";.Explore More PHP Number Patterns!
Mirror patterns like this build strong intuition for symmetric loops and string building.
Symmetry often comes from printing a sequence forward and then printing it backward—exactly what we do here around the center 0.
12 people found this page helpful
