Reverse Alphabet, Diagonal * in PHP

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

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

Output
EDCB*
EDC*A
ED*BA
E*CBA
*DCBA
1

Complete PHP Program (A–E)

Fixed version (5 rows):

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

1

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.

2

Inner loop prints reverse letters

$j counts down from $end to 0, so the default output per row is EDCBA.

3

Swap one position with *

When $j === $i, the current cell becomes *. That creates a diagonal line of stars across the square.

4

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.

Newline
=

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

Reads rows from stdin and clamps to 26 (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 < $rows; $i++) {
    for ($j = $end; $j >= 0; $j--) {
        if ($j === $i) {
            echo '*';
        } else {
            echo $alpha[$j];
        }
    }
    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 18

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

Program 18 →

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