Odd-Length Alphabet Triangle in PHP

What You'll Learn
This PHP program prints odd-length alphabet prefixes: A, ABC, ABCDE, ABCDEFG, ABCDEFGHI.
The key idea is stepping the outer loop by 2, so the row end letter jumps A, C, E, G, I.
⭐ Pattern Output
Five rows, no spaces between letters:
A
ABC
ABCDE
ABCDEFG
ABCDEFGHIComplete PHP Program
Fixed five-row version (ends at I):
<?php
$alpha = range('A', 'Z');
for ($i = 0; $i <= 8; $i += 2) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Outer loop uses i += 2
The end index jumps 0, 2, 4, 6, 8, which maps to A, C, E, G, I.
Inner loop prints the prefix
For each row, print indices 0..i, so every row starts at A and ends at the current odd-step letter.
Odd row lengths
Row lengths are 1, 3, 5, 7, 9. Total output for 5 rows is 25 letters, i.e., 5².
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
Choose how many rows to print. Max 13 rows keeps the last letter within Z (since last index is 2*rows-2).
<?php
echo "Enter the number of rows (max 13): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 13));
$alpha = range('A', 'Z');
$last = 2 * $rows - 2;
for ($i = 0; $i <= $last; $i += 2) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
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 15
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
