Inverted Forward Repeating Alphabet Triangle in PHP

What You'll Learn
This PHP program prints an inverted repeating-letter triangle with forward letters: AAAAA, BBBB, CCC, DD, E.
Compare it with Program 11, which uses the same shrinking width but letters go backward.
⭐ Pattern Output
For rows = 5:
AAAAA
BBBB
CCC
DD
EComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
for ($i = 0; $i < $rows; $i++) {
for ($j = $rows - 1; $j >= $i; $j--) {
echo $alpha[$i];
}
echo PHP_EOL;
}🧠 How It Works
Outer loop chooses the letter
$i goes from 0 to 4, selecting A, B, C, D, E.
Inner loop shrinks the width
The inner loop runs from $rows - 1 down to $i, so it prints 5, 4, 3, 2, 1 characters.
One letter per row
We print $alpha[$i] inside the inner loop, so the same row letter repeats.
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 max of 26:
<?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 = 0; $i < $rows; $i++) {
for ($j = $rows - 1; $j >= $i; $j--) {
echo $alpha[$i];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Compare with Program 11 (reverse letters)
- Use
str_repeat($alpha[$i], $rows - $i)to remove the inner loop - Switch to lowercase using
range('a', 'z') - Add spaces between letters for readability
Avoid
- Allowing
$rows> 26 without handling the alphabet size - Using
<br>in CLI examples (usePHP_EOL)
Key Takeaways
Outer loop selects the row letter (A to E for 5 rows).
Inner loop prints a shrinking number of repeats (5 to 1).
Total printed characters is \(n(n+1)/2\), so runtime is O(n²).
❓ 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 13
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
