Reverse Centered Alphabet Pyramid in PHP

What You'll Learn
This reverse centered alphabet pyramid reuses the row logic from program 28: run the same row routine while the floor index goes down to A, then again from B up to the peak letter so the center row is not duplicated.
⭐ Pattern Output
Nine rows for A to E:
E E E E E E E E E
E D D D D D D D E
E D C C C C C D E
E D C B B B C D E
E D C B A B C D E
E D C B B B C D E
E D C C C C C D E
E D D D D D D D E
E E E E E E E E EComplete PHP Program (A–E)
Fixed version that prints the upper phase, then the lower phase that completes the reverse centered pyramid:
<?php
$alpha = range('A', 'Z');
$k = 4; // 0..4 => A..E
for ($i = $k; $i >= 0; $i--) {
for ($j = $k; $j >= 0; $j--) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
for ($j = 1; $j <= $k; $j++) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
echo PHP_EOL;
}
for ($i = 1; $i <= $k; $i++) {
for ($j = $k; $j >= 0; $j--) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
for ($j = 1; $j <= $k; $j++) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
echo PHP_EOL;
}🧠 How It Works
First phase prints the center row
The loop from $k down to 0 includes $i = 0, so you get the row with A in the middle exactly once.
Second phase walks back up
Start at $i = 1 so the center row is not repeated, and increase to $k.
Same rule at every position
Each printed cell uses ($j > $i) to choose border letter vs floor letter, which keeps the output grid symmetric.
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. Total rows and width are both 2 * rows - 1:
<?php
echo "Enter the number of rows (max 26): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 26));
$alpha = range('A', 'Z');
$k = $rows - 1;
for ($i = $k; $i >= 0; $i--) {
for ($j = $k; $j >= 0; $j--) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
for ($j = 1; $j <= $k; $j++) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
echo PHP_EOL;
}
for ($i = 1; $i <= $k; $i++) {
for ($j = $k; $j >= 0; $j--) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
for ($j = 1; $j <= $k; $j++) {
echo (($j > $i) ? $alpha[$j] : $alpha[$i]) . " ";
}
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 30
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
