Palindromic Alphabet Pyramid in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Ascend + descend

What You'll Learn

This PHP pattern prints palindromic rows: you go up from A to the peak letter, then come back down without repeating the peak.

⭐ Pattern Output

Five rows, no spaces between letters:

Output
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
1

Complete PHP Program (Through E)

Fixed version (5 rows):

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

for ($i = 0; $i < $rows; $i++) {
    // Ascending: A..(A+i)
    for ($j = 0; $j <= $i; $j++) {
        echo $alpha[$j];
    }

    // Descending: (A+i-1)..A (avoid repeating the peak letter)
    for ($k = $i - 1; $k >= 0; $k--) {
        echo $alpha[$k];
    }

    echo PHP_EOL;
}

🧠 How It Works

1

First loop prints the rising half

For row $i, we print A through A+$i. For example, when $i = 2 we print ABC.

2

Second loop mirrors back down

We start from $i - 1 (not $i) so the peak letter is not duplicated. For ABC, we append BA to form ABCBA.

3

Row lengths are odd

Row r (1-based) prints 2r - 1 letters. Over n rows, total letters printed is n^2.

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 rows from stdin and clamps 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 <= $i; $j++) {
        echo $alpha[$j];
    }
    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 19

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

Program 19 →

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