Mirrored Diagonal Number Pattern in PHP

What You’ll Learn
How to print a mirrored diagonal number pattern in PHP using nested loops and equality checks.
Each row prints the row number on left and right diagonals, with spaces in between.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1 1
2 2
3 3
4 4
5Complete PHP Program
First loop prints the left diagonal zone, second loop prints the mirrored right zone.
<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
if ($i == $j) {
echo $j;
} else {
echo " ";
}
}
for ($k = 4; $k >= 1; $k--) {
if ($i == $k) {
echo $k;
} else {
echo " ";
}
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls rows
for ($i = 1; $i <= 5; $i++) determines which row value to place.
Left-side scan
Loop $j = 1..5; print number only when $i == $j, else spaces.
Right-side mirror
Loop $k = 4..1; print when $i == $k, else spaces for mirrored diagonal.
Line break
echo PHP_EOL; moves to the next row.
Mirrored diagonals
The pattern checks two diagonal positions per row, with complexity O(n²).
Variation — User Input (CLI) Version
This version accepts row size from user input (run from terminal with php):
<?php
echo "Enter number of rows: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
echo ($i == $j) ? $j : " ";
}
for ($k = $n - 1; $k >= 1; $k--) {
echo ($i == $k) ? $k : " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use stars or letters instead of numbers on diagonals
- Increase spacing width for better alignment with larger values
- Print full X-shape by extending rows beyond midpoint
- Colorize diagonal values in HTML output mode
- Convert pattern lines into array for testing/assertions
Avoid
- Using non-breaking HTML spaces in CLI-focused code
- Forgetting to adjust right loop bounds when size changes
- Printing both diagonals twice at center intersection
- Skipping input validation for row count
Key Takeaways
Row index equality checks place numbers on diagonals.
Two inner loops create left and mirrored right halves.
Center row merges into a single printed value.
Same approach adapts to symbol-based and X-shaped patterns.
❓ Frequently Asked Questions
$n = 8 (or input 8 in the CLI version) and loops adapt automatically." " with ". " to visualize empty cells.Explore More PHP Number Patterns!
Practice diagonal logic with more creative number-layout challenges.
Diagonal patterns are a classic exercise for visualizing matrix coordinates and understanding row/column index relationships.
12 people found this page helpful
