Reverse Alphabet Pattern (EDCBA to A) in PHP

What You'll Learn
This PHP program prints a reverse alphabet triangle: the first row is the full reverse run, and each next row becomes shorter.
For rows = 5, the output is EDCBA, DCBA, CBA, BA, A.
⭐ Pattern Output
When you run the program with rows = 5:
EDCBA
DCBA
CBA
BA
AComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
$high = $rows - 1; // 4 -> 'E'
for ($i = $high; $i >= 0; $i--) {
for ($j = $i; $j >= 0; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Alphabet array
$alpha = range('A', 'Z'); gives letters A..Z in an array.
Outer loop: starting index decreases
$i counts down from $high to 0, so the first row starts at E, then D, then C, and so on.
Inner loop prints down to A
for ($j = $i; $j >= 0; $j--) prints letters from the row start down to A.
Shrinking reverse rows
Row lengths are 5, 4, 3, 2, 1. Total letters are n(n+1)/2, so runtime is O(n²).
Variation — User Input (CLI) Version
Read rows from standard input (works when you run the file from terminal using php):
<?php
echo "Enter the number of rows (max 26): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 26));
$alpha = range('A', 'Z');
$high = $rows - 1;
for ($i = $high; $i >= 0; $i--) {
for ($j = $i; $j >= 0; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 6 (forward rows ending at E)
- Switch to lowercase using
range('a', 'z') - Add spaces between letters for readability
- Right-align each row with leading spaces
- Try printing a continuous descending stream by changing reset logic
Avoid
- Using
<br>in CLI examples (usePHP_EOL) - Allowing
$rows > 26without handling wrap-around - Using
++when you want descending letters - Mixing HTML output with CLI output without intent
Key Takeaways
Outer loop chooses the row start letter (E, D, C, ...).
Inner loop prints downward to A, so each row is a reverse run.
Total letters are \(n(n+1)/2\), so runtime is O(n²).
❓ Frequently Asked Questions
n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 8
Continue to Program 8 for the next alphabet pattern in PHP.
This pattern keeps the last letter fixed at A, while the start letter moves toward it each row.
10 people found this page helpful
