Right-Aligned Sequential Pyramid in PHP

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

What You'll Learn

This PHP pattern prints letters row-wise using a running counter (k++) and aligns each row to the right by printing fixed-width padding cells.

⭐ Pattern Output

Five rows:

Output
        A
      B C
    D E F
  G H I J
K L M N O
1

Complete PHP Program (5 Rows)

Fixed version. Uses a two-space cell for padding and prints each letter with a trailing space for consistent columns.

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

$k = 0;
$end = $rows - 1;

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

🧠 How It Works

1

One counter streams letters

$k starts at 0 and is incremented only when a letter is printed, so output letters continue A, B, C, ... across rows.

2

Fixed-width scan right-aligns

The inner scan always runs across $rows logical columns. While $j > $i we print padding; otherwise we print letters.

3

Row i prints i+1 letters

Row 0 prints 1 letter, row 1 prints 2 letters, ... row 4 prints 5 letters. Total letters printed is rows*(rows+1)/2.

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 6 so total letters stay within A–Z (1+2+...+6 = 21):

PHP
<?php
echo "Enter the number of rows (max 6): ";
$rows = (int) trim(fgets(STDIN));
$rows = max(1, min($rows, 6));

$alpha = range('A', 'Z');
$k = 0;
$end = $rows - 1;

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

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

Program 23 →

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