Symmetrical Alphabet Pyramid in PHP

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):
A
ABA
ABCBA
ABCDCBA
ABCDEDCBAComplete PHP Program (A–E)
Fixed version (5 rows). Uses ordinary spaces for indentation and PHP_EOL for new lines:
<?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
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.
Ascending letters
The second loop prints $alpha[0] through $alpha[$i] (for example ABC when $i === 2).
Descending mirror
The third loop prints indices $i - 1 down to 0, which mirrors the left side without printing the peak letter twice.
Print the line break
After each row, PHP_EOL moves to the next line. In HTML you would use <br> instead.
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.
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 = 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
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 33
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
