Odd-Length Alphabet Triangle in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
i += 2

What You'll Learn

This PHP program prints odd-length alphabet prefixes: A, ABC, ABCDE, ABCDEFG, ABCDEFGHI.

The key idea is stepping the outer loop by 2, so the row end letter jumps A, C, E, G, I.

⭐ Pattern Output

Five rows, no spaces between letters:

Output
A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
1

Complete PHP Program

Fixed five-row version (ends at I):

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

for ($i = 0; $i <= 8; $i += 2) {
    for ($j = 0; $j <= $i; $j++) {
        echo $alpha[$j];
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Outer loop uses i += 2

The end index jumps 0, 2, 4, 6, 8, which maps to A, C, E, G, I.

2

Inner loop prints the prefix

For each row, print indices 0..i, so every row starts at A and ends at the current odd-step letter.

3

Odd row lengths

Row lengths are 1, 3, 5, 7, 9. Total output for 5 rows is 25 letters, i.e., 5².

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

Choose how many rows to print. Max 13 rows keeps the last letter within Z (since last index is 2*rows-2).

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

$alpha = range('A', 'Z');
$last = 2 * $rows - 2;

for ($i = 0; $i <= $last; $i += 2) {
    for ($j = 0; $j <= $i; $j++) {
        echo $alpha[$j];
    }
    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 15

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

Program 15 →

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