Symmetrical Alphabet Pyramid in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Palindrome rows

What You'll Learn

Each row is a palindrome built from A up to the row letter, then back down. Leading spaces shrink as the row grows so the shape forms a centered pyramid in the console.

⭐ Pattern Output

For 5 rows (A–E):

Output
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA
1

Complete PHP Program (A–E)

Fixed version (5 rows). Uses ordinary spaces for indentation and PHP_EOL for new lines:

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

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

🧠 How It Works

1

Leading spaces

The first inner loop runs rows - 1 - i times and prints one space each time. That pushes the letters right so the pyramid lines up.

2

Ascending letters

The second loop prints $alpha[0] through $alpha[$i] (for example ABC when $i === 2).

3

Descending mirror

The third loop prints indices $i - 1 down to 0, which mirrors the left side without printing the peak letter twice.

4

Print the line break

After each row, PHP_EOL moves to the next line. In HTML you would use <br> instead.

Newline
=

Put it together

The outer loop picks the row index $i. Each row is spaces, then up the alphabet to $i, then back down, then a newline.

2

Variation — User Input (CLI) Version

Clamps rows to 26 (A–Z):

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

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

for ($i = 0; $i < $rows; $i++) {
    for ($j = 0; $j < $rows - 1 - $i; $j++) {
        echo " ";
    }
    for ($k = 0; $k <= $i; $k++) {
        echo $alpha[$k];
    }
    for ($k = $i - 1; $k >= 0; $k--) {
        echo $alpha[$k];
    }
    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 33

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

Program 33 →

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