Symmetric Number Mirror Pattern in PHP

What You’ll Learn
How to print a symmetric number mirror pattern in PHP, where the left side grows as 1..i and the right side mirrors as i..1.
Example final row: 1234554321.
This pattern is a good practice for nested loops plus carefully controlled spacing.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1 1
12 21
123 321
1234 4321
1234554321Complete PHP Program
We print the left numbers, then spaces, then the right mirrored numbers, using conditions based on the current row $i.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
if ($j <= $i) {
echo $j;
} else {
echo " ";
}
}
for ($k = $n; $k >= 1; $k--) {
if ($k > $i) {
echo " ";
} else {
echo $k;
}
}
echo PHP_EOL;
}🧠 How It Works
Set n
$n = 5; controls the maximum digit and number of rows.
Left side: print 1..i
The first inner loop prints digits when $j <= $i; otherwise it prints spaces.
Right side: mirror i..1
The second inner loop counts down from $n to 1 and prints digits only when $k <= $i.
Symmetric mirror
As $i increases, the middle gap shrinks until both halves touch.
Variation — User Input (CLI) Version
Let the user choose $n at runtime (run from terminal with php):
<?php
echo "Enter n (e.g., 5): ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
echo ($j <= $i) ? $j : " ";
}
for ($k = $n; $k >= 1; $k--) {
echo ($k > $i) ? " " : $k;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use
printfpadding to align multi-digit values when n is large - Replace spaces with dots while debugging alignment
- Center-align the whole output by adding leading spaces per row
- Build each row as an array and join for precise spacing control
- Make a full diamond by adding a second half where i decreases
Avoid
- Mixing different space widths between loops (it breaks symmetry)
- Forgetting the newline after each row
- Assuming single-digit numbers when n becomes large
- Skipping validation in the CLI version
Key Takeaways
Left half prints 1..i; right half mirrors as i..1.
Middle spacing shrinks as the row grows.
Nested loops + simple conditions are enough to build symmetry.
For bigger n, use formatting/padding to keep alignment readable.
❓ Frequently Asked Questions
$j > $i and when $k > $i. Keeping both sides consistent preserves symmetry.$j . " " and $k . " " instead of concatenating digits with no spaces.Explore More PHP Number Patterns!
Spacing-based mirror patterns are excellent practice for alignment and loop control.
Many console/terminal patterns become easier if you build each row as a string first, then print it once—especially when alignment matters.
12 people found this page helpful
