V-Shaped Alphabet Pattern in PHP

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

What You'll Learn

We print a letter only when the row index equals the column index. Two scans per row create two diagonals that meet at the bottom, forming a V shape.

⭐ Pattern Output

For 5 rows (A–E):

Output
A       A
 B     B
  C   C
   D D
    E
1

Complete PHP Program (A–E)

Fixed version (5 letters). Uses two-space cells for cleaner alignment:

PHP
<?php
$alpha = range('A', 'Z');
$rows = 5;
$end = $rows - 1;

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

🧠 How It Works

1

Two diagonals

The left half prints when $i === $j. The right half prints when $i === $k.

2

Why the right loop starts at $end - 1

It prevents printing the bottom vertex letter twice on the last row.

3

Width is 2 * rows - 1

Left scan has rows cells; right scan has rows - 1 cells.

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');
$end = $rows - 1;

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

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

Program 32 →

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