Diamond Alphabet & Stars in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Alternating output

What You'll Learn

This PHP pattern creates a vertical diamond. Each row repeats the same letter with * separators, growing to the middle row and then shrinking back down.

⭐ Pattern Output

For half height 5:

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

Complete PHP Program (Half Height 5)

Fixed version (upper 1..5 and lower 4..1):

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

for ($i = 1; $i <= $n; $i++) {
    $ch = $alpha[$i - 1];
    for ($j = 1; $j < 2 * $i; $j++) {
        echo ($j % 2 === 0) ? '*' : $ch;
    }
    echo PHP_EOL;
}

for ($i = $n - 1; $i >= 1; $i--) {
    $ch = $alpha[$i - 1];
    for ($j = 1; $j < 2 * $i; $j++) {
        echo ($j % 2 === 0) ? '*' : $ch;
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Two phases create the diamond

The first loop grows from 1 to n. The second loop shrinks from n-1 to 1 so the middle row is not duplicated.

2

Inner bound gives odd widths

The inner loop runs while $j < 2*$i, so it prints exactly 2*$i - 1 characters per row.

3

Parity alternates letter and star

Odd $j prints the row letter, even $j prints *. That creates B*B, C*C*C, and so on.

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

Reads half height from stdin and clamps to 26 (A–Z):

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

$alpha = range('A', 'Z');

for ($i = 1; $i <= $n; $i++) {
    $ch = $alpha[$i - 1];
    for ($j = 1; $j < 2 * $i; $j++) {
        echo ($j % 2 === 0) ? '*' : $ch;
    }
    echo PHP_EOL;
}

for ($i = $n - 1; $i >= 1; $i--) {
    $ch = $alpha[$i - 1];
    for ($j = 1; $j < 2 * $i; $j++) {
        echo ($j % 2 === 0) ? '*' : $ch;
    }
    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 22

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

Program 22 →

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