Centered Alphabet Pyramid in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Centering with spaces

What You'll Learn

This pattern prints a small centered pyramid. Letters are streamed in order using one counter: first row is A, second row is B C D, third row is E F G H I.

⭐ Pattern Output

Three rows (spaces between letters; leading spaces align columns):

Output
    A
  B C D
E F G H I
1

Complete PHP Program

Fixed version (3 rows, bottom row ends at E):

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

// Caps (indices) for 3 rows: A, C, E -> 0, 2, 4
for ($cap = 0; $cap <= 4; $cap += 2) {
    for ($j = 4; $j >= 0; $j--) {
        if ($j > $cap) {
            echo "  ";
        } else {
            echo $alpha[$k++] . " ";
        }
    }
    echo PHP_EOL;
}

🧠 How It Works

1

One counter streams letters

$k is increased only when a letter is printed, so the alphabet continues across rows.

2

Fixed-width scan centers the content

The inner loop always scans 5 positions (for A..E). While $j > $cap it prints spaces. The rest are letters.

3

Odd widths come from stepping the cap by 2

Caps are 0, 2, 4 which yields 1, 3, 5 printed letters.

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

General version (max 5 rows keeps letters within A–Z for this layout):

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

$alpha = range('A', 'Z');
$k = 0;
$last = 2 * ($rows - 1); // last cap index (0,2,4,6,8,...)

for ($cap = 0; $cap <= $last; $cap += 2) {
    for ($j = $last; $j >= 0; $j--) {
        if ($j > $cap) {
            echo "  ";
        } else {
            echo $alpha[$k++] . " ";
        }
    }
    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 17

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

Program 17 →

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