Reverse Alphabet Pattern (E to EDCBA) in PHP

What You'll Learn
This PHP program prints a reverse alphabet triangle where each row begins with the same ending letter (like E for 5 rows) and then prints letters backward.
For n rows, the last letter is (A + n - 1) and total printed letters are n(n + 1)/2.
⭐ Pattern Output
When you run the program with rows = 5:
E
ED
EDC
EDCB
EDCBAComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
$start = $rows - 1; // 4 -> 'E'
for ($i = 0; $i < $rows; $i++) {
for ($j = $start; $j >= $start - $i; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Create letters A to Z
$alpha = range('A', 'Z'); gives a 0-based array: $alpha[0] = 'A', $alpha[4] = 'E'.
Pick the starting letter
$start = $rows - 1 means for 5 rows you start at index 4, which is 'E'. For n rows you start at 'A' + (n - 1).
Inner loop prints backward
Row $i prints indices from $start down to $start - $i, so each row is one letter longer than the previous.
Reverse alphabet triangle
Total printed letters are n(n + 1)/2, so time complexity is O(n²) for n rows.
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');
$start = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $start; $j >= $start - $i; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print the forward pattern first (Program 1) to compare
- Switch to lowercase using
range('a', 'z') - Insert spaces between letters for readability
- Make the triangle right-aligned by adding leading spaces
- Print a continuous reverse stream by changing where you reset the start
Avoid
- Allowing
$rows > 26without handling wrap-around - Using
<br>in CLI examples (usePHP_EOL) - Off-by-one errors when computing
$start - $i - Mixing HTML output with CLI output without intent
Key Takeaways
Use an alphabet array with range('A', 'Z') for clean indexing.
Row i prints i + 1 letters, growing the triangle by one each row.
Each row starts at 'A' + (rows - 1) and counts down.
Total printed letters are \(n(n+1)/2\), so runtime is O(n²).
❓ Frequently Asked Questions
chr(ord('A') + offset). Using range('A','Z') is often simpler and avoids manual ASCII arithmetic.A and increase the end letter each row.n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 3
Continue to Program 3 for the next alphabet pattern in PHP.
The trick is choosing the row start as rows - 1. Once that index is correct, the inner loop is just counting backward for a row-dependent length.
10 people found this page helpful
