Symmetric Alphabet, Star Center in PHP

What You'll Learn
This PHP program builds a symmetric pattern: left side letters increase from A, the center is filled with *, then the right side mirrors back down to A.
For n = 5, you get ABCDEEDCBA on the first row and then stars grow as the row shortens.
⭐ Pattern Output
For n = 5:
ABCDEEDCBA
ABCD**DCBA
ABC****CBA
AB******BA
A********AComplete PHP Program
Fixed n = 5 version:
<?php
$n = 5;
$alpha = range('A', 'Z');
for ($i = $n; $i >= 1; $i--) {
// Left: A..(A+i-1)
for ($j = 0; $j < $i; $j++) {
echo $alpha[$j];
}
// Center: 2*(n-i) stars
for ($j = 0; $j < 2 * ($n - $i); $j++) {
echo '*';
}
// Right: mirror back down (starts at last left index)
for ($j = $i - 1; $j >= 0; $j--) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Left block (ascending letters)
Print i letters starting from A: for i = 5 you print ABCDE, for i = 4 you print ABCD, etc.
Center block (stars)
The star count is 2*(n-i). It starts at 0 and grows by 2 each row.
Right block (descending mirror)
Start from index i-1 so the middle letter repeats when there are no stars (like the EE in the first row).
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 n from standard input and clamps to 26:
<?php
echo "Enter the number of rows (max 26): ";
$n = (int) trim(fgets(STDIN));
$n = max(1, min($n, 26));
$alpha = range('A', 'Z');
for ($i = $n; $i >= 1; $i--) {
for ($j = 0; $j < $i; $j++) {
echo $alpha[$j];
}
for ($j = 0; $j < 2 * ($n - $i); $j++) {
echo '*';
}
for ($j = $i - 1; $j >= 0; $j--) {
echo $alpha[$j];
}
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 16
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
