Rotating Alphabet Pattern in PHP

What You'll Learn
This pattern prints a constant-width row of letters. It starts at a different letter each row, prints forward to the end, then wraps around back toward A without repeating the starting character.
⭐ Pattern Output
For 5 rows (A–E):
ABCDE
BCDEA
CDEBA
DECBA
EDCBAComplete PHP Program (5 Rows)
Fixed version that prints from A to E:
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1;
for ($i = 0; $i <= $end; $i++) {
for ($j = $i; $j <= $end; $j++) {
echo $alpha[$j];
}
for ($k = $i; $k > 0; $k--) {
echo $alpha[$k - 1];
}
echo PHP_EOL;
}🧠 How It Works
Row start is controlled by $i
Each row starts from a different letter: $alpha[$i].
Forward loop prints $i to $end
This prints the suffix (e.g., for $i = 1 it prints BCDE).
Wrap loop prints the letters before the start
By printing $alpha[$k - 1], the row wraps without duplicating the first letter.
Every row has the same length
Forward prints $end - $i + 1 letters; wrap prints $i letters. Total is always $end + 1.
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 so we stay within 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 <= $end; $i++) {
for ($j = $i; $j <= $end; $j++) {
echo $alpha[$j];
}
for ($k = $i; $k > 0; $k--) {
echo $alpha[$k - 1];
}
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 27
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
