Rotating Alphabet Pattern in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Nested loops

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):

Output
ABCDE
BCDEA
CDEBA
DECBA
EDCBA
1

Complete PHP Program (5 Rows)

Fixed version that prints from A to E:

PHP
<?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

1

Row start is controlled by $i

Each row starts from a different letter: $alpha[$i].

Start
2

Forward loop prints $i to $end

This prints the suffix (e.g., for $i = 1 it prints BCDE).

Forward
3

Wrap loop prints the letters before the start

By printing $alpha[$k - 1], the row wraps without duplicating the first letter.

Wrap
4

Every row has the same length

Forward prints $end - $i + 1 letters; wrap prints $i letters. Total is always $end + 1.

Constant
=

Put it together

The outer loop controls rows, the inner loops control what prints on each row, and PHP_EOL separates the lines.

2

Variation — User Input (CLI) Version

Clamps rows to 26 so we stay within A–Z:

PHP
<?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

It creates an array of uppercase letters so you can print alphabets using simple numeric indexes (0 for A, 1 for B, ...).
PHP_EOL is correct for CLI output and keeps examples consistent for terminal execution. In HTML, you would use <br> instead.
Most pattern programs print O(n) characters per row for n rows, so they are typically O(n2).

Next: PHP Alphabet Pattern 27

Continue to the next program for another alphabet pattern in PHP.

Program 27 →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful