Symmetric Alphabet, Star Center in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Letters + stars

What You'll Learn

This PHP program builds a symmetric pattern: left side letters increase from A, the center is filled with *, then the right side mirrors back down to A.

For n = 5, you get ABCDEEDCBA on the first row and then stars grow as the row shortens.

⭐ Pattern Output

For n = 5:

Output
ABCDEEDCBA
ABCD**DCBA
ABC****CBA
AB******BA
A********A
1

Complete PHP Program

Fixed n = 5 version:

PHP
<?php
$n = 5;
$alpha = range('A', 'Z');

for ($i = $n; $i >= 1; $i--) {
    // Left: A..(A+i-1)
    for ($j = 0; $j < $i; $j++) {
        echo $alpha[$j];
    }

    // Center: 2*(n-i) stars
    for ($j = 0; $j < 2 * ($n - $i); $j++) {
        echo '*';
    }

    // Right: mirror back down (starts at last left index)
    for ($j = $i - 1; $j >= 0; $j--) {
        echo $alpha[$j];
    }

    echo PHP_EOL;
}

🧠 How It Works

1

Left block (ascending letters)

Print i letters starting from A: for i = 5 you print ABCDE, for i = 4 you print ABCD, etc.

2

Center block (stars)

The star count is 2*(n-i). It starts at 0 and grows by 2 each row.

3

Right block (descending mirror)

Start from index i-1 so the middle letter repeats when there are no stars (like the EE in the first row).

4

Print the line break

After building one row, print PHP_EOL to move to the next line. This keeps the output readable in CLI output.

Newline
=

Put it together

The outer loop controls rows, the inner loops control what prints on each row, and PHP_EOL separates the lines.

2

Variation — User Input (CLI) Version

Reads n from standard input and clamps to 26:

PHP
<?php
echo "Enter the number of rows (max 26): ";
$n = (int) trim(fgets(STDIN));
$n = max(1, min($n, 26));

$alpha = range('A', 'Z');

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

    for ($j = 0; $j < 2 * ($n - $i); $j++) {
        echo '*';
    }

    for ($j = $i - 1; $j >= 0; $j--) {
        echo $alpha[$j];
    }

    echo PHP_EOL;
}

❓ Frequently Asked Questions

It creates an array of uppercase letters so you can print alphabets using simple numeric indexes (0 for A, 1 for B, ...).
PHP_EOL is correct for CLI output and keeps examples consistent for terminal execution. In HTML, you would use <br> instead.
Most pattern programs print O(n) characters per row for n rows, so they are typically O(n2).

Next: PHP Alphabet Pattern 16

Continue to the next program for another alphabet pattern in PHP.

Program 16 →

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.

10 people found this page helpful