Right-Aligned Alphabet Pyramid in PHP

What You'll Learn
This pattern uses leading spaces to right-align a growing alphabet triangle. Each row prints letters from A up to the current row letter with spaces between letters.
⭐ Pattern Output
For 5 rows:
A
A B
A B C
A B C D
A B C D EComplete PHP Program (5 Rows)
Fixed right-aligned pyramid (prints A to E):
<?php
$alpha = range('A', 'Z');
$rows = 5;
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j > $i; $j--) {
echo " ";
}
for ($k = 0; $k <= $i; $k++) {
echo $alpha[$k] . " ";
}
echo PHP_EOL;
}🧠 How It Works
Outer loop selects the row
Row index $i grows from 0 to 4, so the number of letters printed becomes 1, 2, 3, 4, 5.
Space loop pushes content to the right
The loop runs while $j > $i. Each step prints two spaces to match the letter cell width.
Letter loop prints A through the row end
The inner loop prints $alpha[0] through $alpha[$i] with spaces between letters.
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 26 (A–Z):
<?php
echo "Enter the number of rows (max 26): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 26));
$alpha = range('A', 'Z');
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j > $i; $j--) {
echo " ";
}
for ($k = 0; $k <= $i; $k++) {
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 28
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
