Right-Aligned Reverse Alphabet Pyramid in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Padding + letters

What You'll Learn

This pattern is a right-aligned triangle where each row prints a descending slice starting at E and ending at the current row letter.

⭐ Pattern Output

Five rows (spacing matters):

Output
        E
      E D
    E D C
  E D C B
E D C B A
1

Complete PHP Program (5 Rows)

Fixed version (E down to A):

PHP
<?php
$alpha = range('A', 'Z');
$rows = 5; // A..E
$end = $rows - 1; // 4 (E)

for ($i = $end; $i >= 0; $i--) {
    // Padding: i cells
    for ($j = 0; $j < $i; $j++) {
        echo "  ";
    }

    // Letters: E down to current i
    for ($j = $end; $j >= $i; $j--) {
        echo $alpha[$j] . " ";
    }

    echo PHP_EOL;
}

🧠 How It Works

1

Outer loop goes from end to start

$i starts at $end (E) and moves down to 0 (A), increasing the number of letters printed each row.

2

Padding shifts the letters to the right

Before printing letters, we print $i padding cells. Each cell is two spaces to match the width of one printed letter plus its trailing space.

3

Descending letters form the row slice

The second loop prints E down to the current row index $i, giving E, then E D, then E D C, and so on.

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

Clamps rows 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 = $end; $i >= 0; $i--) {
    for ($j = 0; $j < $i; $j++) {
        echo "  ";
    }
    for ($j = $end; $j >= $i; $j--) {
        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 24

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

Program 24 →

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