Diamond Alphabet & Stars in PHP

What You'll Learn
This PHP pattern creates a vertical diamond. Each row repeats the same letter with * separators, growing to the middle row and then shrinking back down.
⭐ Pattern Output
For half height 5:
A
B*B
C*C*C
D*D*D*D
E*E*E*E*E
D*D*D*D
C*C*C
B*B
AComplete PHP Program (Half Height 5)
Fixed version (upper 1..5 and lower 4..1):
<?php
$alpha = range('A', 'Z');
$n = 5;
for ($i = 1; $i <= $n; $i++) {
$ch = $alpha[$i - 1];
for ($j = 1; $j < 2 * $i; $j++) {
echo ($j % 2 === 0) ? '*' : $ch;
}
echo PHP_EOL;
}
for ($i = $n - 1; $i >= 1; $i--) {
$ch = $alpha[$i - 1];
for ($j = 1; $j < 2 * $i; $j++) {
echo ($j % 2 === 0) ? '*' : $ch;
}
echo PHP_EOL;
}🧠 How It Works
Two phases create the diamond
The first loop grows from 1 to n. The second loop shrinks from n-1 to 1 so the middle row is not duplicated.
Inner bound gives odd widths
The inner loop runs while $j < 2*$i, so it prints exactly 2*$i - 1 characters per row.
Parity alternates letter and star
Odd $j prints the row letter, even $j prints *. That creates B*B, C*C*C, and so on.
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 half height from stdin and clamps to 26 (A–Z):
<?php
echo "Enter the number of rows (half, max 26): ";
$n = (int) trim(fgets(STDIN));
$n = max(1, min($n, 26));
$alpha = range('A', 'Z');
for ($i = 1; $i <= $n; $i++) {
$ch = $alpha[$i - 1];
for ($j = 1; $j < 2 * $i; $j++) {
echo ($j % 2 === 0) ? '*' : $ch;
}
echo PHP_EOL;
}
for ($i = $n - 1; $i >= 1; $i--) {
$ch = $alpha[$i - 1];
for ($j = 1; $j < 2 * $i; $j++) {
echo ($j % 2 === 0) ? '*' : $ch;
}
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 22
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
