Right-Aligned Sequential Pyramid in PHP

What You'll Learn
This PHP pattern prints letters row-wise using a running counter (k++) and aligns each row to the right by printing fixed-width padding cells.
⭐ Pattern Output
Five rows:
A
B C
D E F
G H I J
K L M N OComplete PHP Program (5 Rows)
Fixed version. Uses a two-space cell for padding and prints each letter with a trailing space for consistent columns.
<?php
$alpha = range('A', 'Z');
$rows = 5;
$k = 0;
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= 0; $j--) {
if ($j > $i) {
echo " ";
} else {
echo $alpha[$k++] . " ";
}
}
echo PHP_EOL;
}🧠 How It Works
One counter streams letters
$k starts at 0 and is incremented only when a letter is printed, so output letters continue A, B, C, ... across rows.
Fixed-width scan right-aligns
The inner scan always runs across $rows logical columns. While $j > $i we print padding; otherwise we print letters.
Row i prints i+1 letters
Row 0 prints 1 letter, row 1 prints 2 letters, ... row 4 prints 5 letters. Total letters printed is rows*(rows+1)/2.
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;
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= 0; $j--) {
if ($j > $i) {
echo " ";
} else {
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 23
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
