Symmetric Decreasing Alphabet Square in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Conditionals

What You'll Learn

This pattern prints a symmetric square where the outer border stays E, and the interior steps down each row until A appears in the center of the last line.

⭐ Pattern Output

For A to E:

Output
E E E E E E E E E
E D D D D D D D E
E D C C C C C D E
E D C B B B C D E
E D C B A B C D E
1

Complete PHP Program (A–E)

Fixed version using $k = 4 (top letter E):

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

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

🧠 How It Works

1

$i controls the row floor

The outer loop decreases from $k to 0, so the plateau letter goes E, D, C, B, A.

2

Two scans build left and right halves

First scan goes from E down to A. Second scan goes from B up to E to mirror the row while keeping A only once.

3

The rule is ($j > $i)

If the column index is above the floor, print the border letter; otherwise print the current floor letter.

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). Note that the total row width becomes 2 * rows - 1:

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

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

Program 29 →

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