Centered Alphabet Pyramid in PHP

What You'll Learn
This pattern prints a small centered pyramid. Letters are streamed in order using one counter: first row is A, second row is B C D, third row is E F G H I.
⭐ Pattern Output
Three rows (spaces between letters; leading spaces align columns):
A
B C D
E F G H IComplete PHP Program
Fixed version (3 rows, bottom row ends at E):
<?php
$alpha = range('A', 'Z');
$k = 0;
// Caps (indices) for 3 rows: A, C, E -> 0, 2, 4
for ($cap = 0; $cap <= 4; $cap += 2) {
for ($j = 4; $j >= 0; $j--) {
if ($j > $cap) {
echo " ";
} else {
echo $alpha[$k++] . " ";
}
}
echo PHP_EOL;
}🧠 How It Works
One counter streams letters
$k is increased only when a letter is printed, so the alphabet continues across rows.
Fixed-width scan centers the content
The inner loop always scans 5 positions (for A..E). While $j > $cap it prints spaces. The rest are letters.
Odd widths come from stepping the cap by 2
Caps are 0, 2, 4 which yields 1, 3, 5 printed 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
General version (max 5 rows keeps letters within A–Z for this layout):
<?php
echo "Enter the number of rows (max 5): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 5));
$alpha = range('A', 'Z');
$k = 0;
$last = 2 * ($rows - 1); // last cap index (0,2,4,6,8,...)
for ($cap = 0; $cap <= $last; $cap += 2) {
for ($j = $last; $j >= 0; $j--) {
if ($j > $cap) {
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 17
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
