Reverse Alphabet, Diagonal * in PHP

What You'll Learn
Each row prints the reverse alphabet sequence (EDCBA) but swaps one position with *. The star shifts one column each row, creating a diagonal.
⭐ Pattern Output
EDCB*
EDC*A
ED*BA
E*CBA
*DCBAComplete PHP Program (A–E)
Fixed version (5 rows):
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1;
for ($i = 0; $i < $rows; $i++) {
for ($j = $end; $j >= 0; $j--) {
if ($j === $i) {
echo '*';
} else {
echo $alpha[$j];
}
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls the row
$i runs from 0 to $rows-1. This value is used to decide where the star appears on that row.
Inner loop prints reverse letters
$j counts down from $end to 0, so the default output per row is EDCBA.
Swap one position with *
When $j === $i, the current cell becomes *. That creates a diagonal line of stars across the square.
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 rows from stdin and clamps 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--) {
if ($j === $i) {
echo '*';
} else {
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 18
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
