Alphabet Pattern E to ABCDE in PHP

What You'll Learn
This PHP program prints a triangle where each row starts one step earlier in the alphabet, but still ends at the same letter (E for 5 rows).
For rows = 5, the output is E, DE, CDE, BCDE, ABCDE.
⭐ Pattern Output
When you run the program with rows = 5:
E
DE
CDE
BCDE
ABCDEComplete 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 - $i; $j <= $end; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Build an alphabet array
$alpha = range('A', 'Z'); makes it easy to print letters by index.
Fix the ending letter
$end = $rows - 1 is the index of the right-edge letter (E for 5 rows). Every row will end at $alpha[$end].
Start earlier each row, print forward
Row $i starts at index $end - $i and prints forward up to $end. So the row length is $i + 1.
Reverse start, forward run
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');
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end - $i; $j <= $end; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 2 (reverse letters within the row)
- Switch to lowercase using
range('a', 'z') - Add spaces between letters (e.g.,
echo $alpha[$j] . " ";) - Right-align the pattern using leading spaces
- Use a different ending letter by setting
$endmanually
Avoid
- Allowing
$rows > 26without handling wrap-around - Using
<br>in CLI examples (usePHP_EOL) - Off-by-one errors in the start index (
$end - $i) - Mixing HTML output with CLI output without intent
Key Takeaways
Row i prints letters from index end - i to end.
The pattern grows by one character per row, like other right-angled triangles.
Each row ends at the same letter, so the right edge stays straight.
Total printed letters are \(n(n+1)/2\), so runtime is O(n²).
❓ Frequently Asked Questions
$end = 25 and keep $rows small enough so $end - ($rows - 1) stays within A..Z.n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 4
Continue to Program 4 for the next alphabet pattern in PHP.
The last letter on row i is always the fixed end letter because the loop always prints up to $end.
10 people found this page helpful
