PHP Diamond Alphabet Pattern

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

What Is This Pattern?

A diamond-shaped alphabet pattern prints only the outline of a diamond: tip A at the top, letters that open to a wide waist, then close back to tip A.

Remember
Rule: upper $i = 0..$n, then lower $i = $n-1..0
      On each row, print $alpha[$col] where $i == $col

    A    
   B B   
  C   C  
 D     D 
E       E
 D     D 
  C   C  
   B B   
    A         ← A–E (9 rows, width 9)

Build it by stacking Program 33 (upper inverted V) and mirroring back from $n - 1 so the waist prints once. Geometry matches the hollow diamond in Star Pattern 9, with letters instead of *.

How to Solve It

Print one hollow alphabet row with two inner loops, then call that idea twice — ascending, then descending past the waist.

MethodIdeaBest for
Dual outer loopsUpper 0..$n, lower $n-1..0, same $j/$k bodiesLearning, interviews, clearest stack of P33
Helper + print_rowOne print_row($i) called from both halvesLess duplication once the geometry clicks

Pseudocode

Pseudocode
$n = ord($end) - ord('A')
printHollowRow($i, $n):
    for $j from $n down to 0:
        echo $alpha[$j] if $i == $j else " "
    for $k from 1 to $n:
        echo $alpha[$k] if $i == $k else " "
    echo PHP_EOL

for $i from 0 to $n:              // upper half
    printHollowRow($i, $n)
for $i from $n - 1 down to 0:     // lower half (skip waist)
    printHollowRow($i, $n)

Cheat sheet

GoalPattern
Scale from end letter$n = ord($end) - ord('A');
Upper halffor ($i = 0; $i <= $n; $i++)
Lower half (no duplicate waist)for ($i = $n - 1; $i >= 0; $i--)
Left diagonal$j from $n down to 0; letter when $i == $j
Right diagonal$k from 1 to $n; letter when $i == $k
Rows / width2 * $n + 1
End the rowecho PHP_EOL; after both inner loops
Upper half aloneProgram 33

Printing Letters vs Starting a New Line

APIEffectUse for
echoStays on the same lineEach letter and each space
echo PHP_EOLEnds the current lineAfter both $j and $k loops

Print cells without a newline, then end the row once.

Live Preview

Change the end letter and the diamond updates instantly — including row and outline-letter counts.

One letter from A to Z. You get 2 * $n + 1 rows where $n = ord(end) - ord('A').

Live result A–E · 9 rows · 16 letters
    A    
   B B   
  C   C  
 D     D 
E       E
 D     D 
  C   C  
   B B   
    A    

Worked Walkthrough — A–D ($n = 3)

Trace each outer value of $i. Letters land where $j == $i or $k == $i. Spaces show as ·.

Half$iPrinted rowLetters
Upper0 (A)···A···1
Upper1 (B)··B·B··2
Upper2 (C)·C···C·2
Upper (waist)3 (D)D·····D2
Lower2 (C)·C···C·2
Lower1 (B)··B·B··2
Lower0 (A)···A···1

Lines: 4 + 3 = 7 = 2×3 + 1. Outline letters: 12 = 4×3. Width of every line: 7.

PHP Programs

Three complete programs: fixed A–E, end-letter input, and a reusable row helper. Use View Output to reveal sample results.

Example 1 — Fixed A–E

Upper $i = 0..4, lower $i = 3..0, same $j/$k bodies.

PHP
<?php
$alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// Upper half: A through E
for ($i = 0; $i <= 4; $i++) {
    for ($j = 4; $j >= 0; $j--) {
        if ($i == $j) {
            echo $alpha[$j];
        } else {
            echo " ";
        }
    }
    for ($k = 1; $k <= 4; $k++) {
        if ($i == $k) {
            echo $alpha[$k];
        } else {
            echo " ";
        }
    }
    echo PHP_EOL;
}

// Lower half: skip duplicate waist
for ($i = 3; $i >= 0; $i--) {
    for ($j = 4; $j >= 0; $j--) {
        if ($i == $j) {
            echo $alpha[$j];
        } else {
            echo " ";
        }
    }
    for ($k = 1; $k <= 4; $k++) {
        if ($i == $k) {
            echo $alpha[$k];
        } else {
            echo " ";
        }
    }
    echo PHP_EOL;
}

How It Works

1. Alphabet table. $alpha[0] is A, $alpha[4] is E.

2. Upper half grows outward. $i runs from 0 to 4. Left $j and right $k print a letter only when they equal $i.

3. Lower half mirrors without a second waist. $i runs from 3 down to 0 with the same inner logic.

4. Break the line. echo PHP_EOL after both inner loops starts the next outline row.

Example 2 — End Letter Input

Read the end letter and scale both phases with $n = ord($end) - ord('A'). Prefer validating a single A–Z character in real apps.

PHP
<?php
echo "Enter end letter (like E): ";
$line = trim(fgets(STDIN));
$end = strtoupper($line[0]);

$n = ord($end) - ord('A');
$alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

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

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

How It Works

1. Prompt and normalize. Read a line, trim it, and take the first character as uppercase.

2. Scale both phases. For end = C, $n = 2 — 5 rows of width 5.

3. Safer input tip. Bare $line[0] warns on empty input. Prefer:

Safer input
$line = strtoupper(trim(fgets(STDIN)));
if (strlen($line) !== 1 || $line < 'A' || $line > 'Z') {
    echo "Enter a single letter A–Z." . PHP_EOL;
    exit;
}
$end = $line;

Example 3 — Helper Function

Extract one row printer so the diamond reads as “upper, then lower.”

PHP
<?php
function print_cell($alpha, $row, $col) {
    echo ($row == $col) ? $alpha[$col] : " ";
}

function print_row($alpha, $n, $i) {
    for ($j = $n; $j >= 0; $j--) {
        print_cell($alpha, $i, $j);
    }
    for ($k = 1; $k <= $n; $k++) {
        print_cell($alpha, $i, $k);
    }
    echo PHP_EOL;
}

$n = 4;
$alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for ($i = 0; $i <= $n; $i++) {
    print_row($alpha, $n, $i);
}

for ($i = $n - 1; $i >= 0; $i--) {
    print_row($alpha, $n, $i);
}

How It Works

1. One row recipe. print_row owns the $j/$k diagonal logic and the row break.

2. Call it twice. Upper half walks $i up; lower half walks $i down from $n - 1.

3. Same shape, less copy-paste. Learn the expanded loops first (Example 1), then refactor when the geometry feels familiar.

Edge Cases & Pitfalls

Check these before calling the solution done.

Lower starts at $n

Double waist

If the second outer loop starts at $i = $n, the widest line prints twice. Use $n - 1.

$k = 0

Duplicate tip A

Right loop must start at $k = 1. Starting at 0 prints two As on the tip rows.

PHP_EOL inside

Broken outline

If echo PHP_EOL sits inside $j or $k, the outline collapses into a column. Call it only after both inner loops.

end = A

Single tip

Upper prints one line; lower never runs. Output is just A — a good sanity check.

Proportional font

Looks skewed in the IDE

Spaces and letters need a monospace font. Proportional fonts make diagonals look uneven.

Bad input

Validate one letter

Empty lines and multi-character input break naive $line[0] indexing — require a single A–Z character.

Time and Space Complexity

ProgramTimeExtra space
Dual loops (Examples 1–2)O(n²)O(1) beyond the alphabet string
Helper function (Example 3)O(n²)O(1) beyond the alphabet string

Lines printed = 2n + 1. Each line walks about 2n + 1 positions across the two inner loops, so work is still quadratic in n. Outline letters grow as 4n for n ≥ 1 (and 1 when n = 0).

Key Takeaways

  • Compose halves: upper 0..$n then lower $n-1..0 — Program 33 with one seam fix.
  • Diagonal rule: letter only when $i == $j or $i == $k; everything else is a space.
  • Break the row: call echo PHP_EOL only after both inner loops.
  • Complexity: O(n²) time; O(1) extra space beyond the alphabet string.

One line: print hollow alphabet rows for $i = 0..$n, then again for $i = $n-1..0, starring only the diagonals.

Frequently Asked Questions

The first outer loop grows i from 0 through n (A through the end letter) using the inverted-V inner loops. The second outer loop shrinks i from n-1 through 0 with the same inner loops, mirroring the top without repeating the widest row.
Because the widest row is already printed at the end of the first part. Starting the second part at n again would duplicate that waist line.
Yes. Program 34 is Program 33 printed for A..end and then mirrored back for (end-1)..A using the same inner loops.
echo stays on the same line. echo PHP_EOL ends the current line. Letters and spaces use echo; the row break uses echo PHP_EOL after both inner loops.
For n = ord(end) - ord('A'), total rows are (n+1) + n = 2n+1. For A..E, n is 4 and you get 9 rows.
Width is also 2n+1: n+1 columns from the left block and n columns from the right block.
O(n²) because there are Theta(n) rows and each row scans Theta(n) positions across both blocks.
Use trim(fgets(STDIN)), require a single A–Z character after strtoupper, and reject empty or multi-character input.

Did you know?

Two phases with identical inner loops. Phase 1 prints A..E using two diagonal scans (left: E..A, right: B..E). Phase 2 prints D..A to mirror the top without repeating the widest E row. For $n = ord($end) - ord('A'), total rows and width are both 2n + 1.

Next: Number Patterns

Move from alphabet outlines to number-based pattern tutorials.

Number patterns →

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