Reverse Alphabet Pattern (EDCBA to E) in PHP

What You'll Learn
In this pattern, every row begins with the same letter (E for 5 rows). Each next row gets shorter by dropping the last character.
Output for rows = 5: EDCBA, EDCB, EDC, ED, E.
⭐ Pattern Output
EDCBA
EDCB
EDC
ED
EComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
$end = $rows - 1; // 4 -> 'E'
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= $i; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Build the alphabet array
range('A','Z') creates ['A','B','C',...,'Z'].
Fix the first letter
$end is constant. The inner loop always starts at $end, so every row starts with E (for 5 rows).
Shorten rows by raising the stop
As $i increases, the inner loop stops sooner ($j >= $i), producing 5, 4, 3, 2, 1 characters.
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 standard input and clamps to a max of 26:
<?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 >= $i; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 7 (moving first letter each row)
- Use lowercase letters with
range('a','z') - Add spaces between letters for readability
- Right-align each row using leading spaces
Avoid
- Using
<br>for line breaks in CLI code (usePHP_EOL) - Allowing
$rows> 26 without handling the alphabet size
Key Takeaways
The inner loop always starts from the top letter (E for 5 rows).
The outer loop increases the stop index, so each line becomes shorter.
Total output is \(n(n+1)/2\) letters, so runtime is O(n²).
❓ Frequently Asked Questions
$rows so that $end = $rows - 1 points to the letter you want (e.g., 3 gives D as the first letter).range('A','Z'). Clamping avoids out-of-range indices.Continue to PHP Alphabet Pattern 9
Next up: another pattern variation to practice loop boundaries.
If you fix the start ($j = $end) and only change the stop ($j >= $i), you get triangles where the left edge stays constant.
10 people found this page helpful
