Palindromic Alphabet Pyramid in PHP

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:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBAComplete PHP Program (Through E)
Fixed version (5 rows):
<?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
First loop prints the rising half
For row $i, we print A through A+$i. For example, when $i = 2 we print ABC.
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.
Row lengths are odd
Row r (1-based) prints 2r - 1 letters. Over n rows, total letters printed is n^2.
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
Reads rows from stdin and clamps 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 = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
for ($k = $i - 1; $k >= 0; $k--) {
echo $alpha[$k];
}
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 19
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
