Symmetric Alphabet Pyramid in PHP

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops

What You’ll Learn

Print centered palindromic rows — A, ABA, ABCBA, up to ABCDEDCBA — by padding with spaces, climbing A..i, then mirroring (i-1)..A without repeating the middle letter. Compare Program 18 and Program 24 for related palindrome pyramids. Includes a live preview, worked PHP examples, edge cases, and complexity.

Three Stages

Pad + up + mirror

Spaces, ascending A..i, descending (i-1)..A.

Centering

Leading spaces

Pad so each row sits under the widest base.

Bridge n

$n = $k - 1

Then --$n mirrors without a double peak.

Palindrome

2i+1 letters

Each row climbs to i and mirrors back to A.

Live Preview

Top letter

Pick a top letter (A–F) and draw the pyramid.

O(n²)

Complexity

n rows × O(n) spaces and letters each.

Introduction

A symmetric alphabet pyramid centers growing palindromes so the peak letter of each row sits in the middle and the sides mirror around it.

In PHP you pad with spaces, print A..i, then use a bridge index so the descending half starts at i-1 and never repeats the center.

Why it matters?

It combines centering, ascending char loops, and careful mirroring — a core trio for many pyramid and diamond alphabet labs.

Key Highlights

Pad

Leading spaces center rows.

Ascend

Print A through i.

Mirror

Print (i-1) down to A.

One peak

Bridge n skips a double center.

In short: for each row $i, print $end-$i spaces, print A..$i, set $n = $k-1, print --$n for $i steps, then echo PHP_EOL.

📝 Problem & Approach

Given a top letter (or fixed E), print a centered pyramid of alphabet palindromes ending at that letter.

PHP
// Five rows (top = E)
//     A
//    ABA
//   ABCBA
//  ABCDCBA
// ABCDEDCBA

Inputs & Outputs

ItemTypeDescription
top / endstring / intTop letter; $end = ord($top) - ord('A') (4 for E). Rows = end+1.
Printed outputtextCentered palindrome rows from A up to the top letter.

Minimal workflow

Pseudocode
$end = ord($top) - ord('A')
for i from 0 to end:
    print (end - i) spaces
    for k from 0 to i:                 // ascending A..i
        print letter[k]
    $n = $k - 1                          // peak index
    repeat i times:
        print letter[--$n]              // (i-1)..A
    print newline

Approach comparison

ApproachIdeaBest for
Bridge variable$n = $k-1 then --$n for the mirrorMatching this classic sample
Explicit second loopfor ($p = $i-1; $p >= 0; $p--) echo $alpha[$p]When you want clearer bounds

⚡ Quick Reference

GoalPattern
Alphabet + end$alpha = str_split("ABCDEFG..."); $end = 4;
Rowsfor ($i = 0; $i <= $end; $i++)
Leading spacesfor ($j = $end; $j > $i; $j--) echo " ";
Ascendingfor ($k = 0; $k <= $i; $k++) echo $alpha[$k];
Mirror$n = $k - 1; for ($m = 0; $m < $i; $m++) echo $alpha[--$n];
Inverted V nextSee Program 33

📋 Pad vs Ascend vs Mirror

Four roles that build each centered palindrome row.

spaces
pad

Centers the row under the base

k = 0..i
up

Ascending half including the peak

--$n
mirror

Descending half without the peak

echo PHP_EOL
break

Ends the row after all three stages

Context

When This Pattern Shows Up

Reach for this when teaching centered palindromes with a carefully skipped peak letter.

  1. After diagonal Vs

    Switch from sparse diagonals to filled centered pyramids.

  2. Palindrome drills

    Practice ascending then mirroring without a double center.

  3. Bridge-variable style

    Learn the classic $n = $k - 1 / --$n idiom.

  4. Bridge to Program 33

    Next opens an inverted V with diagonal letters.

  5. Not a UI layout tool

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

Key benefit: pad, ascend to the peak, then mirror with --$n is the cleanest classic way to print centered alphabet palindromes.

🔮 Live Preview

Choose a top letter from A to F and draw the symmetric alphabet pyramid in the browser.

Try E (classic sample) or C (smaller pyramid). Preview allows A–F. Use a monospace view for centering.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed A–E, user-chosen top letter, and an explicit-mirror rewrite. Click View Output to reveal sample console results.

📚 Getting Started

Print five centered palindrome rows from A to ABCDEDCBA.

Example 1 — Fixed A–E

Matches the reference logic using a bridge variable $n = $k - 1 to print the descending half.

PHP
<?php
$alpha = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

for ($i = 0; $i <= 4; $i++) {
    for ($j = 4; $j > $i; $j--)
        echo " ";

    for ($k = 0; $k <= $i; $k++)
        echo $alpha[$k];

    $n = $k - 1;
    for ($m = 0; $m < $i; $m++)
        echo $alpha[--$n];

    echo PHP_EOL;
}

How It Works

When i = 2, spaces pad twice, ascending prints ABC, then --$n prints B AABCBA. The peak C is printed only once.

📈 Practical Variant

Let the user pick the top letter (like E).

Example 2 — Top Letter Input

The loops adapt to the new size automatically. Prefer validating a single A–Z character from the CLI input string in real apps.

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

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

for ($i = 0; $i <= $end; $i++) {
    for ($j = $end; $j > $i; $j--)
        echo " ";

    for ($k = 0; $k <= $i; $k++)
        echo $alpha[$k];

    $n = $k - 1;
    for ($m = 0; $m < $i; $m++)
        echo $alpha[--$n];

    echo PHP_EOL;
}

How It Works

$end = ord($top) - ord('A') scales padding, ascending, and mirror loops together. For top = C you get three centered rows.

⚡ Clearer Mirror

Same pyramid with an explicit descending loop instead of --$n.

Example 3 — Explicit Mirror Loop

Often easier to read: after printing A..$i, loop $p from $i-1 down to 0.

PHP
<?php
$end = 4;
$alpha = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

for ($i = 0; $i <= $end; $i++) {
    for ($j = $end; $j > $i; $j--)
        echo " ";

    for ($k = 0; $k <= $i; $k++)
        echo $alpha[$k];

    for ($p = $i - 1; $p >= 0; $p--)
        echo $alpha[$p];

    echo PHP_EOL;
}

How It Works

The explicit $p = $i - 1 .. 0 loop makes the skipped peak obvious. Output matches the bridge-variable version exactly.

🧠 How the Algorithm Prints Rows

1

Add leading spaces

Loop j from end down while j > i to center the pyramid under the widest row.

Padding
2

Print ascending half

Loop k = 0..i and print alpha[k] so the row climbs from A to the peak letter.

Up
3

Mirror without duplicating the center

Set $n = $k - 1, then print --$n for i steps so the tail is (i-1)..A.

Mirror
4

Letter count is 2i+1

Ascending prints i+1 letters; descending prints i letters. Together with spaces, the pyramid stays centered.

Width
=

Centered palindromes

Each row climbs from A to the row letter, then mirrors back to A — O(n²) time.

🔎 Worked Walkthrough — Top = E (end = 4)

Trace padding, ascending half, and mirrored descending half for each row.

iSpacesAscendingMirrorPrinted row
04A(none)A
13ABAABA
22ABCBAABCBA
31ABCDCBAABCDCBA
40ABCDEDCBAABCDEDCBA

After ascending, k = i + 1, so $n = $k - 1 = i. The first --$n lands on i - 1.

Use Cases

Where this symmetric alphabet pyramid shows up beyond the homework prompt.

1. Palindrome Labs

Clearest demo of climb-then-mirror alphabet rows.

Example: start the mirror at i and watch a double peak.

2. Centering Practice

Reuse leading-space padding for other pyramids.

Example: change j > i to j >= i and see a shift.

3. Bridge-Variable Idiom

Practice $n = $k - 1 then --$n.

Example: rewrite with explicit p = i-1..0 (Example 3).

4. Index Mapping

Scale with $end = ord($top) - ord('A').

Example: grow from E to H without rewriting loops.

5. Complexity Intuition

Growing palindromes make O(n²) easy to see.

Example: row lengths 1+3+5+7+9 = 25 letters.

6. Bridge to Program 33

Next draws an inverted V with diagonal letters.

Example: continue to Program 33.

Pro Tip: say “pad, A..i, then (i-1)..A” before coding — that story prevents a double peak like ABCCBA.

Advantages

Why this pattern earns a spot after V-shaped diagonals.

  1. 1. Instant Visual Feedback

    Bad padding or a double peak shows up immediately.

  2. 2. Clear Three-Stage Story

    Pad, ascend, and mirror are easy to explain separately.

  3. 3. Scales Cleanly

    Change end and the whole pyramid grows.

  4. 4. Two Equivalent Styles

    Bridge --$n or explicit p = i-1..0 both work.

Pro Tip: learn the reference bridge style first if you are matching exam code; switch to the explicit mirror when readability matters more.

Usage Tips

Small habits that keep symmetric alphabet pyramids clean.

  1. 1. Start the Mirror at i-1

    Starting at i duplicates the peak letter.

  2. 2. Keep Space Loop as j > i

    Using j >= i adds an extra leading space.

  3. 3. Set end from the Top Letter

    Use $end = ord($top) - ord('A') so scaling stays automatic.

  4. 4. Validate Top Letter Input

    Require a single A–Z character; normalize case if needed.

  5. 5. Check Centering in Monospace

    Proportional fonts hide whether spaces really align.

Pro Tip: if you see ABCCBA, the mirror almost certainly started at the peak instead of i - 1.

Common Pitfalls

Mistakes that commonly break symmetric alphabet pyramids.

  1. 1. Duplicating the Center Letter

    Mirroring from i instead of i-1 prints the peak twice.

    → Use $n = $k - 1 then --$n, or loop p = i - 1 .. 0.

  2. 2. Extra Leading Space

    Using j >= i shifts the whole pyramid right.

    → Keep for (j = end; j > i; j--).

  3. 3. Top Letter Past Z

    Char math can walk past the alphabet.

    → Validate a single A–Z letter.

  4. 4. Blind First-Character Read

    Empty lines or multi-character input can pick the wrong character.

    → Validate after trimming.

  5. 5. Forgetting echo PHP_EOL

    All rows glue into one long line.

    → Call echo PHP_EOL after the three stages.

Edge Cases

Check these inputs before calling the solution done.

top = A

Single letter

Output is just A (no spaces, no mirror).

top = E

Classic sample

Five rows through ABCDEDCBA.

top = C

Smaller pyramid

A / ABA / ABCBA (Example 2).

Lowercase

Case mismatch

Normalize with strtoupper if needed.

Bad input

Empty / multi-char

Validate before taking the first character.

Spaced

Readability

Print alpha[k] + " " without changing bounds.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Duplicate the peak on purpose

  • Start the mirror at i once
  • Confirm why the sample starts at i-1

2. Rewrite with explicit p

  • Use Example 3’s descending loop
  • Keep the same padding and ascending half

3. Scale to H

  • Set top = H and recompute end
  • Check the base is ABCDEFGHGFEDCBA

4. Continue to Program 33

  • Build an inverted V alphabet pattern
  • See Program 33

Notes

  • Three stages. Pad, ascend A..i, then mirror (i-1)..A.
  • After ascending, k = i + 1, so $n = $k - 1 restores the peak before --$n.
  • Letter count on row i is 2i + 1 (plus leading spaces).
  • Program 33 switches to an inverted V-shaped alphabet pattern.

Quick Takeaway: pad for centering, print A..i, mirror from i-1 down to A, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Bridge / input (Examples 1–2)O(n²)O(1) (plus alphabet source)
Explicit mirror (Example 3)O(n²)O(1)

For n rows each row prints O(n) spaces and letters combined, so total work is O(n²).

Wrap Up

🎉 Conclusion

The symmetric alphabet pyramid combines centering, ascending letters, and a careful mirror that skips the peak. Master the classic A…ABCDEDCBA sample, then try user input and the explicit-mirror rewrite.

Practice the three examples above, then continue to Program 33’s inverted V-shaped alphabet pattern.

Pad with spaces, print A..i, mirror with $n = $k - 1 and --$n, then break the line.

💡 Best Practices

✅ Do

  • Pad with j > i leading spaces
  • Mirror from i - 1 down to A
  • Derive end from the top letter
  • Validate a single A–Z top letter for input variants
  • State O(n²) when asked about complexity

❌ Don’t

  • Start the mirror at the peak (duplicates the center)
  • Use j >= i for padding
  • Hard-code end without updating the alphabet source
  • Skip validating top-letter input
  • Call echo PHP_EOL inside any of the three stages

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

Print the symmetric alphabet pyramid the beginner-friendly way.

5
Core concepts
> 02

Ascend

A..i

Code
- 03

Mirror

(i-1)..A

Code
n 04

Bridge

$n = $k-1; --$n

Idiom
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

It prints A..i ascending, then prints (i-1)..A descending. This mirrors the left half without repeating the center letter.
After the ascending loop, $k is one past the peak letter. Setting $n = $k-1 makes $n equal the peak, and then --$n starts the descending half from the previous letter.
The padding shifts each row to the right so the pyramid is centered under the widest row.
O(n²) for n rows because each row prints O(n) spaces and letters.
After printing A..i, the mirror part starts from i-1 down to A. That avoids duplicating the peak letter.
Use trim(fgets(STDIN)), take the first character after strtoupper, require A–Z, and reject empty or multi-character tokens.
Ascending prints i+1 letters and descending prints i letters, so the row has 2i+1 letters before counting spaces.
Program 18 is another palindromic alphabet pyramid approach. This page follows the classic bridge-variable style with $n = $k-1 and --$n.

Did you Know? 🔊

Each row has three stages: leading spaces for centering, then letters A..i ascending, then letters (i-1)..A descending. The reference keeps a bridge variable $n = $k - 1 after the ascending loop and prints --$n to avoid duplicating the center letter.

Continue to Alphabet Pattern 33

Next up: inverted V-shaped alphabet patterns that open downward from a single A at the top.

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