Right-Aligned Reverse Alphabet Pyramid in PHP

What You'll Learn
This pattern is a right-aligned triangle where each row prints a descending slice starting at E and ending at the current row letter.
⭐ Pattern Output
Five rows (spacing matters):
E
E D
E D C
E D C B
E D C B AComplete PHP Program (5 Rows)
Fixed version (E down to A):
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1; // 4 (E)
for ($i = $end; $i >= 0; $i--) {
// Padding: i cells
for ($j = 0; $j < $i; $j++) {
echo " ";
}
// Letters: E down to current i
for ($j = $end; $j >= $i; $j--) {
echo $alpha[$j] . " ";
}
echo PHP_EOL;
}🧠 How It Works
Outer loop goes from end to start
$i starts at $end (E) and moves down to 0 (A), increasing the number of letters printed each row.
Padding shifts the letters to the right
Before printing letters, we print $i padding cells. Each cell is two spaces to match the width of one printed letter plus its trailing space.
Descending letters form the row slice
The second loop prints E down to the current row index $i, giving E, then E D, then E D C, and so on.
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');
$end = $rows - 1;
for ($i = $end; $i >= 0; $i--) {
for ($j = 0; $j < $i; $j++) {
echo " ";
}
for ($j = $end; $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 24
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
