Inverted V-Shaped Alphabet Pattern in PHP

What You'll Learn
This pattern places letters on two diagonals that move outward as the row letter increases. Row A prints only once, then rows B through E print the same letter twice.
⭐ Pattern Output
For 5 rows (A–E):
A
B B
C C
D D
E EComplete PHP Program (A–E)
Fixed version. Uses two-space cells for consistent alignment:
<?php
$alpha = range('A', 'Z');
$rows = 5;
$end = $rows - 1;
for ($i = 0; $i < $rows; $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
Left diagonal from high-to-low columns
The first loop walks column indices from $end down to 0 and prints only when $i === $j.
Right diagonal skips A
The second loop starts at 1 (B). This ensures the first row prints only one A.
Width is 2 * rows - 1
There are rows cells on the left and rows - 1 on the right.
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 = $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 Alphabet Pattern 34
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
