Sequential Decreasing Alphabet Triangle in PHP

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

What You'll Learn

This pattern prints consecutive letters while the row length decreases by one on each line. A single counter (k++) ensures the alphabet continues across rows.

⭐ Pattern Output

For 5 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 (5, 4, 3, 2, 1 letters):

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

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

🧠 How It Works

1

k streams the alphabet

$k starts at 0 and increments for every printed letter. Because it never resets, output continues A, B, C... across all rows.

2

Row length decreases by one

The inner loop starts at $rows - 1 and ends at $i. As $i increases, the loop runs fewer times.

3

Total letters printed is triangular

For rows = 5, total letters are 5 + 4 + 3 + 2 + 1 = 15, ending at O.

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;

for ($i = 0; $i < $rows; $i++) {
    for ($j = $rows - 1; $j >= $i; $j--) {
        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 26

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

Program 26 →

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