Diamond Diagonal Number Pattern in PHP

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Top + Bottom Halves

What You’ll Learn

The diamond diagonal pattern prints Program 53’s diagonal mirror rows for $i = 1..$n, then mirrors them vertically with a second loop $i = $n-1..1. For $n = 5 you get nine rows forming a full X diamond. This tutorial covers both outer loops, $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).

Vertical Mirror

2nd loop

Second outer loop runs $i = $n-1..1 — same row logic, reversed order.

Live Preview

3–12 for n

Pick size n and draw the full diamond diagonal pattern instantly in the browser.

O(n²)

Complexity

2n-1 rows × 2n-1 cells per row — total work grows as n².

Introduction

A diamond diagonal number pattern is Program 53 mirrored vertically. The top half prints rows 1..$n; the bottom half repeats rows $n-1..1. Row 1 and the last row both show 1 1; the middle row shows a single center digit.

In PHP: first outer loop for ($i = 1; $i <= $n; $i++), then second for ($i = $n - 1; $i >= 1; $i--). Each iteration runs the same inner diagonal loops and ends with echo PHP_EOL.

Why it matters?

It combines diagonal row printing with vertical mirroring — a classic diamond pattern technique.

Key Highlights

Outer loop i

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

Main + mirror

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

Top + Bottom Halves

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

Series Foundation

Builds on Program 53 diagonal mirror; continue to Program 55 diagonal-fill triangle.

In short: top loop $i=1..$n, bottom loop $i=$n-1..1; each row uses $i==$j and $i==$k inner loops, then echo PHP_EOL.

📝 Problem & Approach

Given $n = 5, print nine lines — top half rows 1..5, then bottom half rows 4..1.

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

Inputs & Outputs

ItemTypeDescription
$nintPattern size — top-half row count; full output has 2n-1 rows (typically n ≥ 1).
i, jintRow index i; column j for main diagonal, column k for mirror diagonal.
Printed outputtext2n-1 rows total and 2n-1 cells per row — diamond dimensions.

Minimal workflow

Pseudocode
for i from 1 to n: print diagonal row ($i==$j, $i==$k)
for i from n-1 down to 1: print same diagonal row
each row: j loop + k loop, then newline

Approach comparison

ApproachIdeaBest for
Two diagonal loopsif ($i==$j) echo $j else echo " "; mirror loop with $i==$kFixed width — 2n-1 cells per row
Vertical mirrorSecond outer loop $i = $n-1..1 repeats row logic in reverseFull diamond — 2n-1 rows total
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;
Top half loopfor ($i = 1; $i <= $n; $i++)
Bottom half loopfor ($i = $n - 1; $i >= 1; $i--)
Main diagonalfor ($j = 1; $j <= $n; $j++) — print when $i == $j
Mirror diagonalfor ($k = $n - 1; $k >= 1; $k--) — print when $i == $k
Non-diagonal cellecho " ");
Row breakecho PHP_EOL; after both halves
Program 53 contrastProgram 53 prints only the top n rows; this adds a second outer loop to mirror vertically

📋 Top Half vs Bottom Half vs Row Logic

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

Top half
for ($i = 1; $i <= $n; $i++)

Prints rows 1 through n — same as Program 53.

Bottom half
for ($i = $n - 1; $i >= 1; $i--)

Mirrors top half — starts at n-1 to skip duplicate middle row.

Row logic
j loop: $i==$j
k loop: $i==$k ($k=$n-1..1)

Identical inner loops in both outer halves — main and mirror diagonals.

Learning tip
trace n=3

Full diamond: 5 rows — top 1..3, bottom 2..1.

Context

When This Pattern Shows Up

Reach for this pattern when teaching vertical mirroring, diagonal conditions, and full diamond output.

  1. First lab exercise

    Classic follow-up after Program 53 diagonal mirror — adds vertical mirroring.

  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 53 (top half only), then continue to Program 55 diagonal-fill triangle.

  5. Not a UI layout tool

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

Key benefit: one program that locks in vertical mirroring, diagonal conditions, and O(n²) thinking.

🔮 Live Preview

Choose pattern size $n and draw the full diamond diagonal 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 nine rows for $n = 5 — top half plus mirrored bottom half.

Example 1 — Fixed $n = 5

Hard-coded size — top half loop 1..$n, bottom half $n-1..1, same diagonal row logic.

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

for ($i = $n - 1; $i >= 1; $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

The first outer loop prints rows 1..5 (Program 53 output). The second loop prints rows 4..1, mirroring vertically. Row 1 and row 9 both show 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;
}

for ($i = $n - 1; $i >= 1; $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

Same two outer loops as Example 1; only the size comes from user input.

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

for ($i = $n - 1; $i >= 1; $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 two outer loops and diagonal logic; digits become * on both halves.

🧠 How the Algorithm Builds the Diamond

1

Set up

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

Setup
2

Top half loop

for ($i = 1; $i <= $n; $i++) — prints n rows (Program 53 output).

Loop
3

Bottom half loop

for ($i = $n - 1; $i >= 1; $i--) — mirrors top half; starts at $n-1 to skip duplicate middle row.

Diagonals
4

Row logic (both halves)

Each row: j loop with $i==$j, k loop with $i==$k, then echo PHP_EOL.

Break
=

Full diamond complete

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

🔎 Worked Walkthrough — n = 3 full diamond

Trace how top half (rows 1..3) and bottom half (rows 2..1) combine into five output lines.

PhaseOuter iOutput line
Top half11 1
Top half22 2
Top half33
Bottom half22 2
Bottom half11 1

Five rows total for n=3. Bottom half starts at i=2, not 3, so the middle row is not duplicated.

Use Cases

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

1. Teaching Top + Bottom Halves

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 PHP_EOL vs print 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 → 9 rows × 9 cells = 81 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 print 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 diamond diagonal 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 print inside both inner loops; echo PHP_EOL only after they finish.

  2. 2. Bottom Half Starts at n

    Starting the second outer loop at $i = $n duplicates the middle row — the diamond gets an extra widest line.

    → Start the bottom half at $i = $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. Mirror Loop Starts at n

    Starting at k = n duplicates the center column within a row.

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

  5. 5. Unchecked fgets(STDIN) Input

    Letters or empty input throw invalid input 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 outer loops and inner bounds.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single line

Output is one line: 1 — bottom half 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. Bottom half bounds

  • Try bottom loop $i = $n..1 instead of $n-1..1
  • Observe middle-row duplication

4. Next in series

  • Continue with Program 55 diagonal-fill triangle
  • Compare full diamond vs Program 53 top half only

Notes

  • Cell count. Total checks ≈ (2n-1)² (e.g. 81 cells for n=5).
  • print 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: top loop $i=1..$n, bottom loop $i=$n-1..1; each row uses $i==$j and $i==$k inner loops, 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 diamond diagonal pattern combines Program 53 row logic with a vertical mirror loop — a natural step after single-half diagonal 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 55 for the diagonal-fill number triangle pattern.

Keep bottom half at $i = $n-1..1 and echo PHP_EOL after each row — one break per outer iteration.

💡 Best Practices

✅ Do

  • Explain top loop 1..$n, bottom loop $n-1..1, and diagonal checks 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 bottom half at $i = $n (duplicates middle row)
  • Start mirror loop at k = n (duplicates center column)
  • 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 diamond diagonal pattern

Print Program 53 top half, then mirror rows $n-1..1 for a full X diamond.

5
Core concepts
02

Outer loops

Top: 1..$n; bottom: $n-1..1

Code
03

Diagonal checks

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

Logic
n 04

Fixed width

2n-1 cells/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Program 53 prints only $n rows (the top half). Program 54 adds a second outer loop from $n-1 down to 1 to mirror the output vertically.
Starting at $n would duplicate the middle row (the widest point). $n-1 down to 1 mirrors without repeating the center.
For size $n, the diamond has 2*$n-1 rows: $n for the top half and $n-1 for the bottom half.
At $i=$n, both diagonals meet at the same position, so only one digit appears on the center row.
Yes. Use a variable $n — both outer loops reuse the same diagonal row logic.
Replace the printed digit with * when $i==$j or $i==$k in both outer loops — see Example 3.
O(n²) for (2*$n-1) rows. Each row checks O(n) cells in two inner loops.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you Know? 🔊

Program 54 prints the diagonal mirror pattern (Program 53) for rows 1..$n, then repeats the same logic for rows $n-1..1 — forming a full diamond with numbers on both diagonals.

Continue to Program 55

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

Program 55 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