V-Shaped Alphabet Pattern in PHP

What You'll Learn
We print a letter only when the row index equals the column index. Two scans per row create two diagonals that meet at the bottom, forming a V shape.
⭐ Pattern Output
For 5 rows (A–E):
A A
B B
C C
D D
EComplete PHP Program (A–E)
Fixed version (5 letters). Uses two-space cells for cleaner alignment:
<?php
$alpha = range('A', 'Z');
$rows = 5;
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $rows; $j++) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = $end - 1; $k >= 0; $k--) {
echo ($i === $k) ? ($alpha[$k] . " ") : " ";
}
echo PHP_EOL;
}🧠 How It Works
Two diagonals
The left half prints when $i === $j. The right half prints when $i === $k.
Why the right loop starts at $end - 1
It prevents printing the bottom vertex letter twice on the last row.
Width is 2 * rows - 1
Left scan has rows cells; right scan has rows - 1 cells.
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 (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 < $rows; $j++) {
echo ($i === $j) ? ($alpha[$j] . " ") : " ";
}
for ($k = $end - 1; $k >= 0; $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 Alphabet Pattern 32
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
