Symmetric Alphabet, Star Center in PHP

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

What You’ll Learn

Build rows that mirror letters from both ends, while * fills the center gap as the letter half shortens. For top = 'E', the output begins with ABCDEEDCBA and ends with A********A. Includes a live preview, worked PHP examples, edge cases, and complexity.

Shape Rule

Left | stars | right

Each row: A..end, then even stars, then end..A.

Outer Loop

End letter countdown

for ($i = $top; $i >= 'A'; $i--) picks the letter half end.

Three Parts

Prefix, gap, mirror

Print left letters, 2*(ord($top)-ord($i)) stars, then mirrored letters.

Fixed Width

2n chars / row

Every row stays the same length as letters shrink and stars grow.

Live Preview

1–13 rows

Pick a row count and draw the symmetric star-center pattern in the browser.

O(n²)

Complexity

n rows × 2n chars = O(n²); extra memory stays O(1).

Introduction

A symmetric alphabet pattern with a star center keeps a fixed row width while swapping letter space for stars. The left half shrinks from A..top toward A, the center grows with an even number of * characters, and the right half mirrors the left.

In PHP you usually solve it with an outer countdown plus three inner loops (or a string shortcut for the stars): left letters, stars, then mirrored letters, then echo PHP_EOL.

Why it matters?

It is a classic multi-part row exercise: prefix, gap, and mirror. Once that clicks, hollow diamonds, butterfly patterns, and other fixed-width symmetric shapes become much easier.

Key Highlights

Three Segments

Left letters, center stars, right mirror.

Even Star Gap

Stars = 2*(ord($top) - ord($i)) — always even.

Constant Width

Every row has exactly 2n characters.

Double Middle

First row doubles the peak letter when stars = 0.

In short: for each end letter i from top down to A, print A..i, then 2*(top-i) stars, then i..A, then break the line.

📝 Problem & Approach

Given a positive integer rows (or a fixed top letter like 'E'), print a fixed-width symmetric pattern of alphabet halves with a growing star center.

PHP
// First 5 rows (conceptual shape)
// ABCDEEDCBA
// ABCD**DCBA
// ABC****CBA
// AB******BA
// A********A

Inputs & Outputs

ItemTypeDescription
rowsintNumber of lines (typically 1–26). Top letter = chr(ord('A') + $rows - 1).
Printed outputtextEach row has width 2*rows: left letters + even stars + mirrored letters.

Minimal workflow

Pseudocode
$top = 'E'
for $i from $top down to 'A':
    for $j from 'A' to $i: echo $j
    $stars = 2 * (ord($top) - ord($i))
    for $s from 1 to $stars: echo '*'
    for $m from $i down to 'A': echo $m
    echo PHP_EOL

Approach comparison

ApproachIdeaBest for
Three nested loopsLeft + stars + right explicitlyLearning and interviews
str_repeat("*", $stars)Build the gap in one callShorter production-style demos

⚡ Quick Reference

GoalPattern
Walk row endsfor ($i = $top; $i >= 'A'; $i--)
Left halffor ($j = 'A'; $j <= $i; $j++) echo $j;
Star gapint stars = 2 * (ord($top) - ord($i));
Right halffor ($m = $i; $m >= 'A'; $m--) echo $m;
Star shortcutecho str_repeat("*", $stars);
End the rowecho PHP_EOL;

📋 echo vs Stars vs Mirror

Same row — three roles that must stay in order.

Left echo $j
A..i

Ascending prefix for this row’s end letter

Center stars
2*(top-i)

Even gap that grows as letters shrink

Right echo $m
i..A

Descending mirror of the left half

echo PHP_EOL
new line

Only after all three parts finish

Context

When This Pattern Shows Up

Reach for this shape when practicing multi-part fixed-width rows.

  1. After simpler triangles

    Combine ascending, descending, and fill in one row.

  2. Center-gap drills

    Same idea as hollow stars: letters shrink, filler grows.

  3. Symmetry checks

    Visual test that left and right halves stay mirrors.

  4. Gateway to Program 16

    Next: centered alphabet pyramids with leading spaces.

  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 prefix + gap + mirror thinking while keeping row width constant.

🔮 Live Preview

Choose a row count between 1 and 13 and draw the symmetric alphabet / star-center pattern in the browser.

Try 5 (top = E) or 4 (top = D). Max 13 keeps top within A–M for a readable preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed top letter, CLI input, and a str_repeat star shortcut. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with three explicit inner loops.

Example 1 — Fixed top = 'E'

Hard-coded height — ideal for first demos and screenshots.

PHP
<?php
$top = 'E';

for ($i = $top; $i >= 'A'; $i--) {
    for ($j = 'A'; $j <= $i; $j++) {
        echo $j;
    }

    $stars = 2 * (ord($top) - ord($i));
    for ($s = 1; $s <= $stars; $s++) {
        echo "*";
    }

    for ($m = $i; $m >= 'A'; $m--) {
        echo $m;
    }

    echo PHP_EOL;
}

How It Works

When i = 'E', left prints ABCDE, stars = 0, right prints EDCBA — hence the doubled E. As i falls, the letter halves shrink and the even star gap grows, keeping width 10.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Compute $top = chr(ord('A') + $rows - 1), then reuse the same three-part row. Check is_numeric() in real apps.

PHP
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));

$top = chr(ord('A') + $rows - 1);

for ($i = $top; $i >= 'A'; $i--) {
    for ($j = 'A'; $j <= $i; $j++) {
        echo $j;
    }

    $stars = 2 * (ord($top) - ord($i));
    for ($s = 1; $s <= $stars; $s++) {
        echo "*";
    }

    for ($m = $i; $m >= 'A'; $m--) {
        echo $m;
    }

    echo PHP_EOL;
}

How It Works

For rows = 4, top is 'D' and each row has width 8. Clamp rows to 1–26 so top stays within A–Z.

⚡ Shortcut Style

Same shape with a one-call star gap.

Example 3 — str_repeat("*", $stars)

Keep the letter loops; build the center gap in one call.

PHP
<?php
$top = 'E';

for ($i = $top; $i >= 'A'; $i--) {
    for ($j = 'A'; $j <= $i; $j++) {
        echo $j;
    }

    $stars = 2 * (ord($top) - ord($i));
    echo str_repeat("*", $stars);

    for ($m = $i; $m >= 'A'; $m--) {
        echo $m;
    }

    echo PHP_EOL;
}

How It Works

str_repeat("*", $stars) creates the whole gap at once. Great once you understand the three-part row; keep the explicit star loop for exams that ask you to show all bounds.

🧠 How the Algorithm Prints Rows

1

Set up

Use fgets(STDIN) when reading input. Fix top or compute it from rows.

Setup
2

Outer loop (end letter)

i goes from top down to 'A' — that is the letter half end.

E → A
3

Left + stars

Print A..i, then 2*(ord($top) - ord($i)) stars for the center gap.

Prefix + gap
4

Mirror + break

Print $i..A, then echo PHP_EOL to end the fixed-width row.

Mirror
=

Pattern complete

n rows × 2n characters = O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — top = 'E'

Trace each outer-loop value of i and check left, stars, and right.

iLeftStarsRightFull row
'E'ABCDE0EDCBAABCDEEDCBA
'D'ABCD2DCBAABCD**DCBA
'C'ABC4CBAABC****CBA
'B'AB6BAAB******BA
'A'A8AA********A

Every row has length 10 = 2×5. Total characters: 5×10 = 50.

Use Cases

Where this multi-part row pattern shows up beyond the homework prompt.

1. Multi-Part Rows

Clearest demo that one row can be several loops in sequence.

Example: omit the right half and watch symmetry break.

2. Fixed-Width Shapes

Letters shrink while filler grows so width stays constant.

Example: count chars on every row — always 2n.

3. Mirror Practice

Ascending then descending loops over the same end letter.

Example: swap right loop direction and break the palindrome.

4. Fill-Character Variants

Swap * for #, spaces, or digits once the structure works.

Example: use str_repeat("#", $stars).

5. Complexity Intuition

Constant-width rows make O(n²) obvious: n × 2n prints.

Example: n = 10 → 200 characters.

6. Input Validation Labs

Pair with is_numeric() and 1–26 clamps for A–Z.

Example: reject rows > 26.

Pro Tip: say “left, gap, right” before coding — that story prevents forgetting the mirror half or misplacing echo PHP_EOL.

Advantages

Why this pattern earns a spot after simpler alphabet triangles.

  1. 1. Instant Visual Feedback

    Wrong star count or missing mirror shows up immediately as broken symmetry.

  2. 2. Composable Skills

    Reuses ascending loops, descending loops, and fill loops together.

  3. 3. Easy to Customize

    Change the fill character or skip the doubled middle with small edits.

  4. 4. Clear Complexity Story

    Fixed width 2n makes O(n²) easy to explain in interviews.

Pro Tip: learn the three-loop version first; treat str_repeat("*", $stars) as a polish shortcut afterward.

Usage Tips

Small habits that keep symmetric star-center code clean.

  1. 1. Name the Three Parts

    Comment or structure code as left / stars / right so the order stays obvious.

  2. 2. Prefer is_numeric()

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

  3. 3. Keep PHP_EOL Last

    Only call echo PHP_EOL; after left, stars, and right all finish.

  4. 4. Use Even Star Counts

    Stick to 2*(ord($top) - ord($i)) so the gap stays even and centered.

  5. 5. Dry-Run One Small n

    Trace rows = 3 (ABCCBA / AB**BA / A****A) on paper first.

Pro Tip: if the first row is ABCDEDCBA (one E), you started the right half at i - 1 — fine as a variant, but not this page’s default.

Common Pitfalls

Mistakes that commonly break symmetric star-center patterns.

  1. 1. Forgetting the Mirror Half

    You get only left letters and stars — no symmetry.

    → Always print i..A after the star gap.

  2. 2. Wrong Star Formula

    Using ord($top) - ord($i) (not doubled) misaligns the center and shrinks the width.

    → Keep stars = 2 * (ord($top) - ord($i)).

  3. 3. PHP_EOL Too Early

    Breaking after the left half splits one logical row into three lines.

    → Call echo PHP_EOL only after left + stars + right.

  4. 4. Blind (int) Cast

    Letters or empty input need validation — cast carefully.

    → Check is_numeric() and re-prompt on failure.

  5. 5. Reversing the Left Half

    Printing the left side descending changes the intended pattern.

    → Left is always ascending A..i; right is descending i..A.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single doubled letter

Output is AA (left A + right A, zero stars).

rows = 0

Empty pattern

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

First row

Doubled peak

Expect ...EE... style middle when stars = 0.

rows > 26

Past Z

Clamp or error — char math leaves A–Z.

Bad input

Non-numeric input

Non-numeric input becomes 0 — check is_numeric() first.

Fill char

Not only *

Same structure works with #, spaces, or digits.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Single middle letter

  • Start right half at i - 1 when stars = 0
  • First row becomes ABCDEDCBA

2. Change the fill

  • Use # or spaces instead of *
  • Keep the 2*(top-i) count

3. Safe input loop

  • Use is_numeric() until 1 <= rows <= 26
  • Then draw the pattern

4. Continue to Program 16

Notes

  • Fixed width. Each row has 2n characters; total work is 2n² — O(n²).
  • Star count must be 2*(ord($top) - ord($i)) for this centered even gap.
  • First row doubles the peak letter because left ends at i and right starts at i.
  • Validate 1 <= rows <= 26 for interactive A–Z programs.

Quick Takeaway: left A..i, even star gap, right i..A, then break the line — that is the whole pattern.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Three loops (Examples 1–2)O(n²)O(1)
str_repeat("*", $stars) (Example 3)O(n²)O(n) temporary gap string per row

Each of the n rows prints exactly 2n characters, so total prints are 2n².

Wrap Up

🎉 Conclusion

The symmetric alphabet / star-center pattern is a multi-part nested-loop exercise with lasting payoff: prefix, even gap, and mirror on a fixed-width row. Master the three-loop version, then optionally shorten the star gap with str_repeat("*", $stars).

Practice the three examples above, then continue to Program 16’s centered alphabet pyramid.

Print left, then 2*(ord($top)-ord($i)) stars, then the mirror — and call echo PHP_EOL only after all three parts.

💡 Best Practices

✅ Do

  • Structure each row as left / stars / right
  • Use stars = 2 * (ord($top) - ord($i)) for an even center
  • Call echo PHP_EOL only after all three parts
  • Validate 1 <= rows <= 26 for interactive programs
  • State O(n²) via n rows × 2n characters

❌ Don’t

  • Skip the mirrored right half
  • Use a non-doubled star count for this shape
  • Break the line between the three parts
  • Print the left half in reverse
  • Allow rows > 26 without a clear policy

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

Print the symmetric star-center pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

End letter top→A

Code
* 03

Star gap

2*(top-i) stars

Code
04

PHP_EOL

After all three parts

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The left half prints A..E, and the right half prints E..A. When there are zero stars on the first row, E appears as the last character of the left half and the first character of the right half.
Stars per row are 2*(ord($top) - ord($end)). For top=E: 0, 2, 4, 6, 8 stars as end goes E, D, C, B, A.
Because it is computed as 2*(ord($top) - ord($i)), which is always a multiple of 2.
Yes. You can start the right half from chr(ord($i) - 1) instead of $i when there are zero stars, so the first row becomes ABCDEDCBA.
echo sends output without adding a line break. PHP_EOL ends the current line with a portable newline. Letters and stars use echo; the row break uses echo PHP_EOL after all three parts.
O(n²) for n rows. Each row prints a total of 2n characters (letters + stars), repeated across n rows.
NaN
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int, then clamp rows between 1 and 26 so bad input does not walk past Z.

Did you Know? 🔊

Each row is: ascending letters from A to the row end, then 2*(ord($top) - ord($end)) stars, then descending letters back to A. The middle letter appears twice when star count is 0, producing ABCDEEDCBA on the first row. Total width stays constant at 2n characters per row.

Continue to Alphabet Pattern 16

Next up: a centered alphabet pyramid with leading spaces and a running letter counter.

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