Sequential Alphabet Triangle in PHP

What You'll Learn
Each row is wider than the last, and letters stay in order across the whole triangle: A, then B C, then D E F, up to K L M N O for 5 rows.
Unlike patterns that reset letters per row, this one uses a single counter that keeps advancing.
⭐ Pattern Output
For rows = 5 (letters separated by spaces):
A
B C
D E F
G H I J
K L M N OComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
$k = 0;
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$k++] . ($j === $i ? '' : ' ');
}
echo PHP_EOL;
}🧠 How It Works
Alphabet array + counter
$alpha holds A..Z and $k is the next index to print.
Outer loop controls row width
Row $i prints $i+1 letters.
Inner loop prints and advances
$k++ runs once per printed letter, so the alphabet continues across rows.
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
Reads rows from standard input and clamps to a safe max (6) to stay within A–Z:
<?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 = 0; $j <= $i; $j++) {
echo $alpha[$k++] . ($j === $i ? '' : ' ');
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Remove spaces by echoing only the letter
- Switch to lowercase using
range('a','z') - Add wrap logic (mod 26) if you want more rows
Avoid
- Resetting
$kinside the outer loop (you will repeat A at every row) - Letting
$kexceed 25 without wrap logic
❓ 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 14
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
