Right-Aligned Reverse Pyramid in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Right alignment

What You'll Learn

This PHP pattern prints a reverse suffix (A, BA, CBA, …) and pads each row on the left so the letters align to the right in a fixed-width grid.

⭐ Pattern Output

Monospace (leading spaces matter):

Output
    A
   BA
  CBA
 DCBA
EDCBA
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 chooses the row peak

Row $i decides the longest letter printed on that line: A, then B, then C, etc.

2

Inner loop scans the row from right to left

$j counts down from $end to 0. That scan direction prints letters in reverse order (like CBA).

3

Condition $j > $i prints spaces

While the scan index is larger than the current peak, we print spaces. That creates the right alignment. When $j <= $i, we print letters.

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--) {
        echo ($j > $i) ? ' ' : $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 21

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

Program 21 →

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