Symmetric Decreasing Alphabet Square in PHP

What You'll Learn
This pattern prints a symmetric square where the outer border stays E, and the interior steps down each row until A appears in the center of the last line.
⭐ Pattern Output
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 EComplete PHP Program (A–E)
Fixed version using $k = 4 (top letter E):
<?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;
}🧠 How It Works
$i controls the row floor
The outer loop decreases from $k to 0, so the plateau letter goes E, D, C, B, A.
Two scans build left and right halves
First scan goes from E down to A. Second scan goes from B up to E to mirror the row while keeping A only once.
The rule is ($j > $i)
If the column index is above the floor, print the border letter; otherwise print the current floor letter.
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). Note that the total row width becomes 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;
}❓ 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 29
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
