PHP Alphabet Triangle Pattern (Right-Angled)

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

An alphabet right-angled triangle prints a left-aligned staircase of letters: row i is the first i letters of the alphabet.

Remember
Rule: on row i, print A through the i-th letter

A
AB
ABC
ABCD
ABCDE     ← 5 rows

In PHP you solve it with two nested for loops: the outer loop picks the end letter, the inner loop restarts at A and echos each character, then echo PHP_EOL moves to the next line. Once this clicks, reverse triangles and other letter patterns become much easier.

How to Solve It

Two ways to emit the same shape — start with nested letter loops, then optionally shorten with substr.

MethodIdeaBest for
Nested letter loopsOuter = end letter; inner = A..endLearning, interviews, exams
substr($letters, 0, $i)Take the first $i letters of A–Z in one callShorter demos once loops click

Pseudocode

Pseudocode
for $end from 'A' to lastLetter:
    for $ch from 'A' to $end:
        echo $ch
    echo PHP_EOL

Cheat sheet

GoalPattern
Walk each end letterfor ($i = 'A'; $i <= $last; $i++)
Print A..$ifor ($j = 'A'; $j <= $i; $j++) echo $j;
End the rowecho PHP_EOL;
Last letter from rows$last = chr(ord('A') + $rows - 1);
One-line row shortcutecho substr($letters, 0, $i) . PHP_EOL;
Reverse laterCount down from the top letter → Program 2

Printing Letters vs Starting a New Line

APIEffectUse for
echoStays on the same lineEach letter
echo PHP_EOLEnds the current lineAfter the inner loop

Print letters without a newline, then end the row once.

Live Preview

Change the row count and the alphabet triangle updates instantly — including the triangular letter total.

Whole numbers from 1 to 26. Tap a chip or type a value — the preview redraws as you go.

Live result 5 rows · last E · 15 letters
A
AB
ABC
ABCD
ABCDE

Worked Walkthrough — $rows = 4

Trace each outer-loop end letter and the letters printed on that row.

End $iInner $jPrinted rowLetters
'A'A..AA1
'B'A..BAB2
'C'A..CABC3
'D'A..DABCD4

Total letter prints: 1 + 2 + 3 + 4 = 10 = 4×5/2. That triangular sum is why time is O(n²).

PHP Programs

Three complete programs: fixed end letter, CLI input, and a substr shortcut. Use View Output to reveal sample results.

Example 1 — Fixed through 'E'

Hard-coded end letter — ideal for first demos and screenshots (5 rows).

PHP
<?php
for ($i = 'A'; $i <= 'E'; $i++) {
    for ($j = 'A'; $j <= $i; $j++) {
        echo $j;
    }
    echo PHP_EOL;
}

How It Works

1. Outer loop picks the end letter. $i runs from 'A' to 'E' — one row per end letter.

2. Inner loop restarts at A. For each $i, $j runs from 'A' to $i, so the row is A..$i.

3. Print letters, then break the line. echo $j stays on the row; echo PHP_EOL after the inner loop starts the next row.

When $i = 'A' you get A; when $i = 'B' you get AB; up through ABCDE.

Example 2 — User Input Version

Read the row count from the CLI. Prefer validating with is_numeric and clamping to 26 (shown in the tip below).

PHP
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
$last = chr(ord('A') + $rows - 1);

for ($i = 'A'; $i <= $last; $i++) {
    for ($j = 'A'; $j <= $i; $j++) {
        echo $j;
    }
    echo PHP_EOL;
}

How It Works

1. Prompt and read. Ask for a row count, then cast the trimmed line to an int.

2. Map rows to an end letter. $last = chr(ord('A') + $rows - 1) — for $rows = 4, $last is 'D'.

3. Same nested-loop core. Only the source of $last changes — the print logic matches Example 1.

4. Safer input tip. Prefer:

Safer input
$raw = trim(fgets(STDIN));
if (!is_numeric($raw)) {
    echo "Enter a whole number from 1 to 26." . PHP_EOL;
    exit;
}
$rows = (int) $raw;
if ($rows < 1 || $rows > 26) {
    echo "Enter a whole number from 1 to 26." . PHP_EOL;
    exit;
}

Example 3 — substr($letters, 0, $i)

Build each row in one call — same shape, no explicit inner letter loop.

PHP
<?php
$rows = 5;
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for ($i = 1; $i <= $rows; $i++) {
    echo substr($letters, 0, $i) . PHP_EOL;
}

How It Works

1. One outer loop. Walk $i from 1 to $rows.

2. Slice the alphabet. substr($letters, 0, $i) returns the first $i characters (A, AB, …).

3. Print and advance. Append PHP_EOL so each slice lands on its own line.

Learn the two-loop version first (Examples 1–2) so you can explain both bounds; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling the solution done.

PHP_EOL inside

Column of letters

If echo PHP_EOL sits inside the inner loop, each letter lands on its own line. Use echo for letters; break the row only after the inner loop.

Wrong bound

Rectangle / wrong length

Inner range must be 'A' through $i. A fixed end always prints the same width.

$rows = 1

Single A

Output is just A on one line — a good sanity check.

$rows > 26

Past Z

chr(ord('A') + $rows - 1) leaves A–Z when $rows > 26. Clamp or reject in interactive programs.

Char ++ past Z

Odd loop stop

PHP letter increment past 'Z' becomes multi-character strings. Cap loops at 26 for alphabet demos.

Bad input

Use is_numeric

Bare (int) fgets(STDIN) turns letters into 0 — validate before the outer loop.

Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
substr (Example 3)O(rows²)O(rows) per temporary row string

Total letters = 1 + 2 + … + n = n(n + 1)/2 — still quadratic in n.

Key Takeaways

  • Rule: row with end letter $i prints A through $i.
  • Two loops: outer = end letter; inner restarts at A.
  • Break the row: call echo PHP_EOL only after the inner loop.
  • Complexity: O(n²) time from the triangular letter count; O(1) extra space for nested loops.

One line: for each end letter $i from 'A' to the last letter, print A through $i, then echo PHP_EOL.

Frequently Asked Questions

The outer loop picks the last letter on each row. The inner loop always restarts at A and prints up through that last letter, so row 1 is A, row 2 is AB, row 3 is ABC, and so on.
Each row is a fresh sequence from A to the current end letter. If you kept advancing a single char across rows, you would get a different pattern (not this right-angled alphabet triangle).
echo sends output without adding a line break. echo PHP_EOL ends the current line with a portable newline. Letters use echo; the row break uses echo PHP_EOL after the inner loop.
Start each row at the top letter and count down — for example E, ED, EDC. See Alphabet Pattern Program 2.
O(n²) where n is the number of rows. Total echo calls equal 1+2+…+n = n(n+1)/2.
Yes. Keep a string of A–Z and print substr($letters, 0, $i) for row length i. Nested letter loops are better for learning; substr is a handy shortcut later.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int, then clamp rows between 1 and 26 so bad input does not walk past Z.
Char math can produce characters beyond Z. Clamp to 26 for A–Z demos, or define a clear wrap/error policy.

Did you know?

Row i prints letters from A through the i-th letter (A, AB, ABC, …). Total letters for n rows is the triangular number n(n+1)/2 — the same count that makes this pattern O(n²).

Next: Reverse Alphabet Triangle

Start each row at the top letter and count down — E, ED, EDC, EDCB…

Program 2 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

12 people found this page helpful