Palindromic Alphabet Pyramid in PHP

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:
A
BAB
CBABC
DCBABCD
EDCBABCDEComplete PHP Program (5 Rows)
Fixed version (A..E):
<?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
Outer loop sets the row letter
Row $i peaks at $alpha[$i] (A, B, C, ...).
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.
Second inner loop prints A..peak
This loop prints from index 0 up to $i, adding the single center A and completing the palindrome.
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.
Put it together
The outer loop controls rows, the inner loops control what prints on each row, and PHP_EOL separates the lines.
Variation — User Input (CLI) Version
Clamps rows to 26 (A–Z):
<?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
PHP_EOL is correct for CLI output and keeps examples consistent for terminal execution. In HTML, you would use <br> instead.Next: PHP Alphabet Pattern 25
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
