Diamond-Shaped Alphabet Pattern in PHP

What You'll Learn
This pattern is built by printing the inverted V from program 33, then printing a mirrored copy below it to close the diamond.
⭐ Pattern Output
For 5 rows (A–E):
A
B B
C C
D D
E E
D D
C C
B B
AComplete PHP Program (A–E)
Fixed version. Uses two-space cells for consistent alignment:
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1;
for ($i = 0; $i <= $end; $i++) {
for ($j = $end; $j >= 0; $j--) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = 1; $k <= $end; $k++) {
echo ($i === $k) ? ($alpha[$k] . " ") : " ";
}
echo PHP_EOL;
}
for ($i = $end - 1; $i >= 0; $i--) {
for ($j = $end; $j >= 0; $j--) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = 1; $k <= $end; $k++) {
echo ($i === $k) ? ($alpha[$k] . " ") : " ";
}
echo PHP_EOL;
}🧠 How It Works
Top half grows to the widest row
$i increases from 0 to $end, so the outline expands until the E row.
Bottom half mirrors back down
Start at $end - 1 so the middle row is not duplicated.
Same two inner loops for every row
The diamond is formed by reusing identical diagonal logic in both phases.
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 26. Here rows means the half-height (top half letters):
<?php
echo "Enter the number of rows (half, max 26): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 26));
$alpha = range('A', 'Z');
$end = $rows - 1;
for ($i = 0; $i <= $end; $i++) {
for ($j = $end; $j >= 0; $j--) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = 1; $k <= $end; $k++) {
echo ($i === $k) ? ($alpha[$k] . " ") : " ";
}
echo PHP_EOL;
}
for ($i = $end - 1; $i >= 0; $i--) {
for ($j = $end; $j >= 0; $j--) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = 1; $k <= $end; $k++) {
echo ($i === $k) ? ($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 Number Pattern Programs
Continue with number pattern tutorials.
10 people found this page helpful
