Decreasing & Increasing Alphabet Rows in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Computed bound

What You'll Learn

Each row stitches two parts: a decreasing run from the row letter down to B, and an increasing run from A to a cap chosen so the total row length stays constant.

⭐ Pattern Output

For 5 rows:

Output
ABCDE
BABCD
CBABC
DCBAB
EDCBA
1

Complete PHP Program (5 Rows)

Fixed version (A–E):

PHP
<?php
$alpha = range('A', 'Z');
$k = 4; // 0..4 => A..E

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

🧠 How It Works

1

Outer loop chooses the row anchor

$i goes from 0 to 4, so the row anchor letter goes A, B, C, D, E.

2

First inner loop prints the decreasing prefix

It prints from $alpha[$i] down to $alpha[1] (B). It stops before A so A won’t be duplicated.

3

Second inner loop fills the remaining width

The cap $k - $i decreases each row so the total letters per row stay at $k + 1.

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 26 (A–Z):

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

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

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

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

Program 31 →

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