Right-Aligned Alphabet Pyramid in PHP

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

What You'll Learn

This pattern uses leading spaces to right-align a growing alphabet triangle. Each row prints letters from A up to the current row letter with spaces between letters.

⭐ Pattern Output

For 5 rows:

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

Complete PHP Program (5 Rows)

Fixed right-aligned pyramid (prints A to E):

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

for ($i = 0; $i < $rows; $i++) {
    for ($j = $end; $j > $i; $j--) {
        echo "  ";
    }
    for ($k = 0; $k <= $i; $k++) {
        echo $alpha[$k] . " ";
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Outer loop selects the row

Row index $i grows from 0 to 4, so the number of letters printed becomes 1, 2, 3, 4, 5.

2

Space loop pushes content to the right

The loop runs while $j > $i. Each step prints two spaces to match the letter cell width.

3

Letter loop prints A through the row end

The inner loop prints $alpha[0] through $alpha[$i] with spaces between 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

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 = 0; $i < $rows; $i++) {
    for ($j = $end; $j > $i; $j--) {
        echo "  ";
    }
    for ($k = 0; $k <= $i; $k++) {
        echo $alpha[$k] . " ";
    }
    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 28

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

Program 28 →

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