Mirrored Alphabet, Spaces in PHP

What You'll Learn
This pattern prints letters on the left, a shrinking space gap, then the mirrored letters on the right. The last row touches in the center as ABCDEEDCBA.
⭐ Pattern Output
Five rows from A to E:
A A
AB BA
ABC CBA
ABCD DCBA
ABCDEEDCBAComplete PHP Program (A–E)
Fixed version (5 rows). Each row does two full-width passes and prints a space slot when the condition fails.
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
// Left pass: A..E, print letters up to i
for ($j = 0; $j <= $end; $j++) {
echo ($j <= $i) ? $alpha[$j] : ' ';
}
// Right pass: E..A, print letters from i down to A
for ($k = $end; $k >= 0; $k--) {
echo ($k > $i) ? ' ' : $alpha[$k];
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls the peak
Row $i is the peak index. Left side prints A..alpha[i]; right side mirrors back down.
Left pass: letters then spaces
While $j <= $i print the letter. After that, print spaces to keep a fixed row width.
Right pass: spaces then letters
While $k > $i print spaces. Then print alpha[$k] down to A to mirror the left side.
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 stdin and clamps 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 = 0; $j <= $end; $j++) {
echo ($j <= $i) ? $alpha[$j] : ' ';
}
for ($k = $end; $k >= 0; $k--) {
echo ($k > $i) ? ' ' : $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 20
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
