Sequential Decreasing Alphabet Triangle in PHP

What You'll Learn
This pattern prints consecutive letters while the row length decreases by one on each line. A single counter (k++) ensures the alphabet continues across rows.
⭐ Pattern Output
For 5 rows:
A B C D E
F G H I
J K L
M N
OComplete PHP Program (5 Rows)
Fixed version (5, 4, 3, 2, 1 letters):
<?php
$alpha = range('A', 'Z');
$rows = 5;
$k = 0;
for ($i = 0; $i < $rows; $i++) {
for ($j = $rows - 1; $j >= $i; $j--) {
echo $alpha[$k++] . " ";
}
echo PHP_EOL;
}🧠 How It Works
k streams the alphabet
$k starts at 0 and increments for every printed letter. Because it never resets, output continues A, B, C... across all rows.
Row length decreases by one
The inner loop starts at $rows - 1 and ends at $i. As $i increases, the loop runs fewer times.
Total letters printed is triangular
For rows = 5, total letters are 5 + 4 + 3 + 2 + 1 = 15, ending at O.
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
Clamps rows to 6 so total letters stay within A–Z (1+2+...+6 = 21):
<?php
echo "Enter the number of rows (max 6): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 6));
$alpha = range('A', 'Z');
$k = 0;
for ($i = 0; $i < $rows; $i++) {
for ($j = $rows - 1; $j >= $i; $j--) {
echo $alpha[$k++] . " ";
}
echo PHP_EOL;
}❓ Frequently Asked Questions
PHP_EOL is correct for CLI output and keeps examples consistent for terminal execution. In HTML, you would use <br> instead.Next: PHP Alphabet Pattern 26
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
