Alphabet Pattern A to EDCBA in PHP

What You'll Learn
This PHP program prints a triangle where the first letter of each row moves forward (A, B, C, D, E), but letters in the row are printed backward down to A.
For rows = 5, the output is A, BA, CBA, DCBA, EDCBA.
⭐ Pattern Output
When you run the program with rows = 5:
A
BA
CBA
DCBA
EDCBAComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
for ($i = 0; $i < $rows; $i++) {
for ($j = $i; $j >= 0; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Alphabet array
$alpha = range('A', 'Z'); gives you an indexable list of letters.
Outer loop picks the row start
Row $i starts from $alpha[$i] (A, then B, then C...).
Inner loop prints backward to A
for ($j = $i; $j >= 0; $j--) prints indices $i, $i-1, ..., 0, so each row ends at A.
Reverse-order rows
Total printed letters are 1+2+…+n = 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');
for ($i = 0; $i < $rows; $i++) {
for ($j = $i; $j >= 0; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 1 (forward letters within the row)
- Switch to lowercase using
range('a', 'z') - Add spaces between letters for readability
- Right-align the triangle with leading spaces
- Print the same logic using
chr()instead ofrange()
Avoid
- Allowing
$rows > 26without handling wrap-around - Using
<br>in CLI examples (usePHP_EOL) - Off-by-one errors (
$j >= 0matters) - Mixing HTML output with CLI output without intent
Key Takeaways
Row i starts at 'A' + i and prints down to 'A'.
The inner loop counts backward, so letters are reversed within each row.
Every row ends at A, so the right edge is fixed.
Total printed 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 5
Continue to Program 5 for the next alphabet pattern in PHP.
This is the mirror idea of patterns where every row ends at the same letter: here, every row ends at A.
10 people found this page helpful
