Sequential Alphabet Triangle in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Nested loops

What You'll Learn

Each row is wider than the last, and letters stay in order across the whole triangle: A, then B C, then D E F, up to K L M N O for 5 rows.

Unlike patterns that reset letters per row, this one uses a single counter that keeps advancing.

⭐ Pattern Output

For rows = 5 (letters separated by spaces):

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

Complete PHP Program

Fixed rows = 5 version:

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

$k = 0;

for ($i = 0; $i < $rows; $i++) {
    for ($j = 0; $j <= $i; $j++) {
        echo $alpha[$k++] . ($j === $i ? '' : ' ');
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Alphabet array + counter

$alpha holds A..Z and $k is the next index to print.

2

Outer loop controls row width

Row $i prints $i+1 letters.

3

Inner loop prints and advances

$k++ runs once per printed letter, so the alphabet continues across rows.

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 standard input and clamps to a safe max (6) to stay within A–Z:

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 = 0; $j <= $i; $j++) {
        echo $alpha[$k++] . ($j === $i ? '' : ' ');
    }
    echo PHP_EOL;
}

💡 Tips for Enhancement

Try These

  • Remove spaces by echoing only the letter
  • Switch to lowercase using range('a','z')
  • Add wrap logic (mod 26) if you want more rows

Avoid

  • Resetting $k inside the outer loop (you will repeat A at every row)
  • Letting $k exceed 25 without wrap logic

❓ 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 14

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

Program 14 →

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