Palindromic Alphabet Pyramid in PHP

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

What You'll Learn

Each row is built by printing letters in descending order (from the row letter down to B), then ascending order (from A up to the row letter). That forms a palindrome with exactly one A in the middle.

⭐ Pattern Output

For 5 rows:

Output
A
BAB
CBABC
DCBABCD
EDCBABCDE
1

Complete PHP Program (5 Rows)

Fixed version (A..E):

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

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

🧠 How It Works

1

Outer loop sets the row letter

Row $i peaks at $alpha[$i] (A, B, C, ...).

2

First inner loop prints the left wing

It prints from the peak index down to 1, so it stops before A. That prevents duplicating A at the join.

3

Second inner loop prints A..peak

This loop prints from index 0 up to $i, adding the single center A and completing the palindrome.

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

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 = $i; $j > 0; $j--) {
        echo $alpha[$j];
    }
    for ($j = 0; $j <= $i; $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 25

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

Program 25 →

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