Alphabet Pattern ABCDE to E in PHP

What You'll Learn
This PHP program prints a triangle where each row starts one letter later (A, then B, then C...) while the end letter stays the same (E for 5 rows).
For rows = 5, the output is ABCDE, BCDE, CDE, DE, E.
⭐ Pattern Output
When you run the program with rows = 5:
ABCDE
BCDE
CDE
DE
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 = $i; $j <= $end; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Alphabet array
$alpha = range('A', 'Z'); gives letters A..Z in an array.
Start index increases each row
Row $i starts at index $i, so the first letter shifts from A to B to C, and so on.
End index stays fixed
$end = $rows - 1 (E for 5 rows). The inner loop prints from $i to $end, so every row ends at the same letter.
Shrinking rows
Total letters printed are 5+4+3+2+1 = 15 for 5 rows, which is n(n+1)/2 in general.
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 = $i; $j <= $end; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 5 (same widths, but each row starts from A)
- Switch to lowercase using
range('a', 'z') - Print only odd-length rows for another variation
- Right-align rows with leading spaces
- Choose a different end letter by setting
$endmanually
Avoid
- Using
<br>in CLI examples (usePHP_EOL) - Allowing
$rows > 26without handling wrap-around - Off-by-one mistakes in the inner loop bound (
$j <= $end) - Mixing HTML output with CLI output without intent
Key Takeaways
Outer loop controls the starting letter; inner loop prints up to a fixed end letter.
Line lengths shrink by one each row: n, n-1, ..., 1.
Total printed letters are \(n(n+1)/2\), so runtime is O(n²).
❓ Frequently Asked Questions
$end = 25 (Z) and keep $rows small enough so $i never exceeds 25.n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 7
Continue to Program 7 for the next alphabet pattern in PHP.
This pattern keeps the right edge fixed while the left edge moves right each row — a useful idea for many “sliding window” style patterns.
10 people found this page helpful
