Right-Aligned Reverse Pyramid in PHP

What You'll Learn
This PHP pattern prints a reverse suffix (A, BA, CBA, …) and pads each row on the left so the letters align to the right in a fixed-width grid.
⭐ Pattern Output
Monospace (leading spaces matter):
A
BA
CBA
DCBA
EDCBAComplete PHP Program (A–E)
Fixed version (5 rows):
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= 0; $j--) {
if ($j > $i) {
echo ' ';
} else {
echo $alpha[$j];
}
}
echo PHP_EOL;
}🧠 How It Works
Outer loop chooses the row peak
Row $i decides the longest letter printed on that line: A, then B, then C, etc.
Inner loop scans the row from right to left
$j counts down from $end to 0. That scan direction prints letters in reverse order (like CBA).
Condition $j > $i prints spaces
While the scan index is larger than the current peak, we print spaces. That creates the right alignment. When $j <= $i, we print letters.
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');
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= 0; $j--) {
echo ($j > $i) ? ' ' : $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 21
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
