Diagonal Mirror Number Pattern in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Two Diagonal Loops

What You’ll Learn

The diagonal mirror pattern prints numbers on the main diagonal and mirror diagonal with spaces elsewhere — forming an X shape. For $n = 5: 1 1, 2 2, 3 3. This tutorial covers $i==$j and $i==$k logic, live preview, worked PHP examples, edge cases, and O(n²) complexity.

Main Diagonal

$i == $j

Left loop prints digit $j when row $i equals column $j.

Mirror Diagonal

$i == $k

Right loop prints digit $k when $i == $k; runs $k = $n-1..1.

Space Fill

else " "

All non-diagonal positions print a space — only two digits per row (except overlap).

Fixed Width

2*$n-1 cells

Each row has exactly 2*$n-1 character positions for size $n.

Live Preview

3–12 for n

Pick a size n and draw the diagonal mirror pattern instantly in the browser.

O(n²)

Complexity

Each row checks 2*$n-1 cells — total work grows as n².

Introduction

A diagonal mirror number pattern places digits only on the main diagonal ($i == $j) and mirror diagonal ($i == $k). Row 1 shows 1 1; row 3 shows digits at both X arms.

In PHP: outer for ($i = 1; $i <= $n; $i++), inner for ($j = 1; $j <= $n; $j++) echo digit or space, inner for ($k = $n-1; $k >= 1; $k--) echo digit or space, then echo PHP_EOL after both halves.

Why it matters?

It is a nested-loop exercise that places digits only on the main and mirror diagonals.

Key Highlights

Outer loop $i

$i = 1..$n picks each row number.

Main + mirror

Left loop echoes when $i==$j; mirror loop echoes when $i==$k.

Two Diagonal Loops

Two loops per row — main diagonal half, then mirror diagonal half.

Series Foundation

Follow Program 52 palindrome rows; continue to Program 54 diamond diagonal.

In short: outer $i=1..$n, inner $j=1..$n with $i==$j, inner $k=$n-1..1 with $i==$k, then echo PHP_EOL.

📝 Problem & Approach

Given $n = 5, print five lines with digits on both diagonals and spaces elsewhere.

PHP
// $n = 5 (conceptual output)
// 1       1
//  2     2 
//   3   3  
//    4 4   
//     5    

Inputs & Outputs

ItemTypeDescription
$nintPattern size — number of rows and diagonal width (typically ≥ 1).
$i, $j, $kintRow index $i; column $j for main diagonal, column $k for mirror diagonal.
Printed outputtext2*$n-1 cells per row — fixed width for size $n.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from 1 to n: print j if $i==$j else space
    for k from n-1 down to 1: print k if $i==$k else space
    newline

Approach comparison

ApproachIdeaBest for
Two diagonal loopsif ($i==$j) echo $j else echo " "; mirror loop with $i==$kFixed width — 2*$n-1 cells per row
fgets(STDIN) input(int) $input after is_numeric($input)User-chosen pattern size
Star diagonalsPrint * on diagonals instead of numbersVisual X-shape without digits — Example 3

⚡ Quick Reference

GoalPattern
Set size$n = 5;
Outer loopfor ($i = 1; $i <= $n; $i++)
Main diagonalfor ($j = 1; $j <= $n; $j++) — echo when $i == $j
Mirror diagonalfor ($k = $n-1; $k >= 1; $k--) — echo when $i == $k
Non-diagonal cellecho " ");
Row breakecho PHP_EOL; after both halves
Program 52 contrastPalindrome rows use increase/decrease loops; this pattern uses $i==$j and $i==$k diagonal checks

📋 Main Diagonal vs Mirror Diagonal vs Combined

How outer row selection, main diagonal loop, mirror diagonal loop, and row breaks work together.

Outer loop
for ($i = 1; $i <= $n; $i++)

Picks row number $i — also the diagonal digit value.

Main diagonal
for ($j = 1; $j <= $n; $j++)
  if ($i == $j) echo $j
  else echo " "

Prints digit at column $j when $i == $j.

Mirror diagonal
for ($k = $n-1; $k >= 1; $k--)
  if ($i == $k) echo $k
  else echo " "

Prints digit when $i == $k; loop starts at $n-1.

Learning tip
trace i=3, n=5

Dry-run row 3 — digits at both diagonal positions: 3 3.

Context

When This Pattern Shows Up

Reach for this pattern when teaching nested loops, diagonal conditions, and fixed-width row output.

  1. First lab exercise

    Classic follow-up after palindrome row patterns like Program 52.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible pattern size.

  4. Gateway to variants

    Compare with Program 52 (palindrome rows), then continue to Program 54 (diamond diagonal).

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in $i==$j, $i==$k, mirror bounds, and O(n²) thinking.

🔮 Live Preview

Choose pattern size $n and draw the diagonal mirror number pattern in the browser.

Try 3, 5, or 8 for n (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed $n = 5, fgets(STDIN) input, and a star-diagonal variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with digits on main and mirror diagonals — X-shaped output.

Example 1 — Fixed $n = 5

Hard-coded size — left loop with $i==$j, mirror loop with $i==$k.

PHP
<?php
$n = 5;

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        if ($i == $j) echo $j;
        else echo " ";
    }
    for ($k = $n - 1; $k >= 1; $k--) {
        if ($i == $k) echo $k;
        else echo " ";
    }
    echo PHP_EOL;
}

How It Works

When $i = 3 and $n = 5, the main diagonal prints 3 at column 3; the mirror diagonal also prints 3. Row 1 prints 1 on both diagonals — 1 1.

📈 Practical Variant

Read $n with fgets(STDIN) for flexible output size.

Example 2 — fgets(STDIN) Input

Same diagonal conditions; size n comes from user input.

PHP
<?php
echo "Enter n: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$n = (int) $input;

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;
}

How It Works

Identical diagonal logic to Example 1; only the size is dynamic.

⚡ Character Variant

Print * on diagonals instead of row numbers.

Example 3 — Star Diagonals

Replace digits with * when $i==$j or $i==$k.

PHP
<?php
$n = 5;

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo $i == $j ? "*" : " ";
    }
    for ($k = $n - 1; $k >= 1; $k--) {
        echo $i == $k ? "*" : " ";
    }
    echo PHP_EOL;
}

How It Works

Same diagonal logic; only the printed character changes from digit to *.

🧠 How the Algorithm Prints Rows

1

Set up

echo is built in; use fgets(STDIN) when reading input. Set $n (e.g. 5).

Setup
2

Loop rows

for ($i = 1; $i <= $n; $i++) — one iteration per output line.

Loop
3

Main and mirror halves

Left loop: echo digit when $i==$j, else space. Mirror loop: echo when $i==$k for $k = $n-1..1.

Diagonals
4

New line after row

echo PHP_EOL; after both inner loops moves to the next row.

Break
=

Diagonal mirror pattern complete

Total checks = n(2n-1)O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — row $i = 3, $n = 5

Trace row 3 to see how main and mirror diagonal checks place digits at both X arms.

HalfCondition hitRow so far
Left (j=1..2)no match  
Left ($j=3)$i==$j → echo 3  3
Left (j=4,5)spaces  3  
Mirror (k=4,5)spaces  3   
Mirror ($k=3)$i==$k → echo 3  3  3
Mirror (k=2,1)spaces  3  3  

Final row: 3 3. Then echo PHP_EOL moves to the next row.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Two Diagonal Loops

Clearest visual proof that outer and inner bounds interact.

Example: use fgets(STDIN) for dynamic n — see Example 2.

2. Mirror Loop Bounds

Mirror loop runs k = n-1 down to 1 so the center column is not duplicated.

Example: compare row 3 with n=5 — digits at columns 3 and 3 on main and mirror diagonals.

3. Console Formatting Drills

Practice echo vs PHP_EOL for multi-line vs single-line output.

Example: use echo "*" when $i==$j or $i==$k — see Example 3.

4. Star Diagonals

Print * when $i==$j or $i==$k instead of the row number.

Example: print $n=5 with * on diagonals and compare the X shape.

5. Complexity Intuition

Fixed width 2n-1 makes O(n²) concrete for beginners.

Example: count cells for n=5 → 5 rows × 9 cells = 45 prints.

6. Input Validation Labs

Pair the pattern with fgets(STDIN) and positive-row checks.

Example: reject n <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner loop roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner PHP courses.

  1. 1. Instant Visual Feedback

    Wrong mirror loop start shows immediately — center column may print twice.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Change $n, use fgets(STDIN), or print * on diagonals instead of numbers.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the $i==$j and $i==$k conditions first; then try fgets(STDIN) input and the star variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use $n for pattern size and $i/$j/$k for row/column indices.

  2. 2. Prefer fgets(STDIN)

    Avoid crashes when the user types letters instead of a number.

  3. 3. Row Break After Inner Loop

    Run left diagonal loop, run mirror loop, then echo PHP_EOL.

  4. 4. Use echo for Diagonal Cells

    Use echo $j or echo " " in the main loop; same for the mirror loop; one echo PHP_EOL per row after both halves.

  5. 5. Dry-Run One Small n

    Trace $n = 5, $i = 3 on paper — expect digits at both diagonal positions.

Pro Tip: if the center column prints twice, check whether the mirror loop starts at n instead of n-1.

Common Pitfalls

Mistakes that commonly break diagonal mirror number patterns.

  1. 1. echo PHP_EOL Inside an Inner Loop

    Each cell lands on its own line — you get a column, not an X-shaped row.

    → Use echo $j or echo " " inside both inner loops; echo PHP_EOL only after they finish.

  2. 2. Mirror Loop Starts at n

    Starting at k = n duplicates the center column — row 3 shows two middle digits instead of one spaced pair.

    → Start the mirror loop at $k = $n - 1 and count down to 1.

  3. 3. Forgetting the Row Break

    Omitting echo PHP_EOL after both inner loops glues all rows onto one line.

    → Always call echo PHP_EOL after both diagonal loops complete.

  4. 4. Wrong Condition in Mirror Loop

    Using $i == $j in the mirror loop prints digits on the wrong diagonal.

    → Main loop uses $i == $j; mirror loop uses $i == $k.

  5. 5. Unchecked fgets(STDIN) Input

    Letters or empty input fail without validation.

    → Call is_numeric($input) before casting to (int).

  6. 6. Hard-coding 5 Everywhere

    Using literal 5 in loop bounds instead of variable $n breaks dynamic input.

    → Use one $n variable for both inner loop bounds.

Edge Cases

Check these inputs before calling the solution done.

$n = 1

Single line

Output is one line: 1 — mirror loop does not run.

$n = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

n < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Large n

Large values produce wide rows — fine for labs; use smaller n for quick demos.

Bad input

Non-numeric fgets(STDIN) input

Unchecked fgets(STDIN) input leaves $n unset — call is_numeric($input) first.

Compact

Single-line form

Use conditional spacing to avoid trailing spaces — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change n

  • Try $n = 3, 6, or 8
  • Verify digits appear only on $i==$j and $i==$k positions

2. Star diagonals

  • Print * instead of numbers on diagonals
  • Compare number X vs star X output

3. Mirror bounds

  • Try mirror loop k = n..1 instead of n-1..1
  • Observe center-column duplication

4. Next in series

  • Continue with Program 54 diamond diagonal
  • Connect to diamond diagonal patterns

Notes

  • Cell count. Total checks ≈ $n(2*$n-1) (e.g. 45 cells for $n=5).
  • echo stays on the line; PHP_EOL advances — mix them carefully.
  • Validate $n > 0 for interactive programs; $n = 1 prints a single digit.
  • Main diagonal: if ($i==$j) echo $j else echo " "; mirror: if ($i==$k) echo $k else echo " ".

Quick Takeaway: outer $i=1..$n, inner $j=1..$n with $i==$j, inner $k=$n-1..1 with $i==$k, then echo PHP_EOL.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed $n = 5 (Example 1)O(n²)O(1)
fgets(STDIN) input (Example 2)O(n²)O(1)
Star diagonals (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The diagonal mirror pattern combines nested loops with diagonal conditions — a natural step after palindrome row patterns. Master the fixed-$n version first, then try fgets(STDIN) input and the star-diagonal variant in Example 3.

Practice the three examples above, then continue to Program 54 for the diamond diagonal number pattern.

Keep echo PHP_EOL after both diagonal halves — one row break per outer iteration.

💡 Best Practices

✅ Do

  • Explain outer $i, main diagonal $i == $j, and mirror diagonal $i == $k before coding
  • Use echo $j or echo " " in left loop; same for mirror loop; then echo PHP_EOL
  • Validate $n ≥ 1 for interactive programs
  • Check fgets(STDIN) return value before using $n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Start mirror loop at $k = $n (duplicates center)
  • Use $i == $j in the mirror loop by mistake
  • Hard-code 5 instead of variable $n
  • Ignore bad console input in user-facing demos
  • Skip the $n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this diagonal mirror pattern

Print digits only where the main and mirror diagonals cross each row.

5
Core concepts
02

Outer loop

$i = 1..$n

Code
03

Diagonal checks

Main: $i==$j; mirror: $i==$k

Logic
n 04

Fixed width

2*$n-1 cells/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

For $i=1, $i==$j prints 1 on the main diagonal and $i==$k prints 1 on the mirror diagonal when $k=1.
At $i=$n, both diagonals meet at the same position in the left half, so only one digit appears.
Starting at $n would duplicate the center column. $k = $n-1 down to 1 mirrors without repeating the middle.
Yes. Use a variable $n — both inner loops run with the same diagonal conditions.
Replace the printed digit with * when $i==$j or $i==$k — see Example 3.
Each row has 2*$n-1 character positions — $n for the left half and $n-1 for the mirror half.
O(n²) for n rows. Each row checks O(n) cells in two loops.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you Know? 🔊

Row $i prints the number on the main diagonal ($i == $j) and on the mirror diagonal ($i == $k). All other cells are spaces — an X-shaped number pattern.

Continue to Program 54

Move on to the diamond diagonal number pattern in the PHP number-pattern series.

Program 54 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful