Inverted Alphabet Pattern (ABCDE to A) in PHP

What You'll Learn
This PHP program prints an inverted alphabet triangle: the first row is the longest and each next row removes the last letter.
For rows = 5, the output is ABCDE, ABCD, ABC, AB, A.
⭐ Pattern Output
When you run the program with rows = 5:
ABCDE
ABCD
ABC
AB
AComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
for ($i = $rows - 1; $i >= 0; $i--) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Alphabet array
$alpha = range('A', 'Z'); gives letters A..Z in an array.
Outer loop shrinks the row length
for ($i = $rows - 1; $i >= 0; $i--) counts down, so each next row prints fewer letters.
Inner loop prints from A each time
The inner loop always starts at 0 (A) and prints up to $i, producing ABCDE, then ABCD, then ABC, and so on.
Inverted triangle
Total printed letters are still n(n+1)/2, so runtime 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');
for ($i = $rows - 1; $i >= 0; $i--) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 1 (growing rows)
- Switch to lowercase using
range('a', 'z') - Right-align the triangle using leading spaces
- Print only even-length rows for another variation
- Try a hollow version by printing only the first and last letters
Avoid
- Using
<br>in CLI examples (usePHP_EOL) - Allowing
$rows > 26without handling wrap-around - Off-by-one errors (
$iand$jbounds matter) - Mixing HTML output with CLI output without intent
Key Takeaways
Use a decreasing outer loop so the number of printed letters shrinks each row.
The inner loop always starts from A, so each line is a prefix.
This is an inverted version of Program 1 (only the outer loop direction changes).
Total printed letters are \(n(n+1)/2\), so runtime is O(n²).
❓ Frequently Asked Questions
str_repeat doesn’t help directly. You can build each row using substrings (e.g., join letters then take a prefix), but nested loops are the clearest for beginners.n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 6
Continue to Program 6 for the next alphabet pattern in PHP.
You can convert the growing version (Program 1) into this inverted version by only changing the direction of the outer loop.
10 people found this page helpful
