PHP Diagonal Mirror Number Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A diagonal mirror number pattern prints digits only on the main diagonal ($i == $j) and the mirror diagonal ($i == $k). Everywhere else is a space — an X shape.

Remember
Rule: for i = 1..n
        left:  if i==j print j else space
        mirror: if i==k print k else space  (k = n-1..1)

1       1
 2     2 
  3   3  
   4 4   
    5         ← n = 5

Unlike Program 52 (palindrome digit runs), here most cells are spaces — only the two diagonals carry values. Program 54 continues with a full diamond diagonal pattern.

How to Solve It

For each row, walk the left half with $i == $j, then the mirror half with $i == $k. End each row with echo PHP_EOL.

MethodIdeaBest for
Fixed nHard-code size; $i==$j / $i==$kLabs and demos
CLI inputSame logic; read $n at runtimeInteractive practice
Star diagonalsPrint * instead of the digitVisual X-shape practice

Pseudocode

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

Cheat sheet

GoalPattern
Set size$n = 5;
Main diagonalif ($i == $j) echo $j; else echo " ";
Mirror halffor ($k = $n - 1; $k >= 1; $k--)
Mirror hitif ($i == $k) echo $k; else echo " ";
End the rowecho PHP_EOL;
Star variantEcho "*" instead of $j / $k

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $j / echo " "Stays on the same lineEach digit or space in both halves
echo PHP_EOLEnds the current lineAfter both halves finish

Build the full row with echo, then break once.

Live Preview

Change n and the diagonal mirror pattern updates instantly.

Whole numbers from 3 to 9. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · width = 9
1       1
 2     2 
  3   3  
   4 4   
    5    

Worked Walkthrough

Trace $n = 5 — where each digit lands on the main and mirror diagonals.

$iMain ($j)Mirror ($k)Printed row
1$j=1 → 1$k=1 → 11 1
2$j=2 → 2$k=2 → 22 2
3$j=3 → 3$k=3 → 33 3
4$j=4 → 4$k=4 → 44 4
5$j=5 → 5(none)5

Row 5 has no mirror hit because $k only goes down to 1 from $n − 1 — the diagonals already meet in the left half.

PHP Programs

Three complete programs: fixed $n = 5, CLI input, and star diagonals. Use View Output for sample results.

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

1. Left half. Columns $j = 1..$n — print $j only when $i == $j (main diagonal).

2. Mirror half. Columns $k = $n − 1..1 — print $k only when $i == $k (mirror diagonal).

3. Spaces elsewhere. Every other cell is a space, so the digits form an X.

Example 2 — User Input

Read $n from the CLI. Prefer is_numeric in real apps (shown in the tip below).

PHP
<?php
echo "Enter n: ";
$n = (int) trim(fgets(STDIN));

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

1. Read n. Ask for a size, then trim(fgets(STDIN)) and cast to int.

2. Same logic. The ternary $i == $j ? $j : " " is just a shorter form of the if/else in Example 1.

3. Safer input tip. Bare (int) casts turn letters into 0. Prefer:

Safer input
echo "Enter n: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 1) {
    echo "Enter a positive whole number." . PHP_EOL;
    exit(1);
}
$n = (int) $input;

Example 3 — Star Diagonals

Same X-shape — print * instead of the diagonal digit.

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

1. Same positions. Still use $i == $j and $i == $k to choose which cells light up.

2. Different glyph. Print * instead of $j or $k — the X shape stays the same.

3. Same width. Each row is still 2n − 1 characters.

Edge Cases & Pitfalls

Check these before calling the solution done.

k from n

Doubled center

Starting the mirror loop at $k = $n reprints the middle column. Always start at $n − 1.

missing spaces

Collapsed X

Skipping the else echo " " branch packs digits together and destroys the diagonal shape.

PHP_EOL inside

echo PHP_EOL inside an inner loop

That splits the X across lines. Call echo PHP_EOL only after both halves finish.

n = 1

Single digit

Output is just 1 — the mirror loop does not run.

n ≤ 0

Empty output

The outer loop never runs. Guard interactive input with $n >= 1.

multi-digit

$n > 9

echo 10 prints two characters and breaks column alignment. Labs usually stick to 1–9.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input / star (Examples 1–3)O(n²)O(1)

There are n rows, and each row checks about 2n − 1 cells, so total work is O(n²).

Key Takeaways

  • Rule: print on $i==$j (left) and $i==$k (mirror); spaces everywhere else.
  • Mirror start: $k = $n − 1 avoids reprinting the center column.
  • echo vs PHP_EOL: digits and spaces stay on the line; echo PHP_EOL advances after both halves.
  • Next step: Program 54 builds a full diamond from diagonal hits.

One line: light up $i==$j and $i==$k; fill the rest with spaces for an X.

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. The mirror loop never hits $k=$n.
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.
echo stays on the same line for each digit or space. echo PHP_EOL ends the row after both halves finish.
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.

Next: Diamond Diagonal Number Pattern

Continue with a full X diamond built from the same diagonal idea.

Program 54 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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