Decreasing & Increasing Alphabet Rows in PHP

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:
ABCDE
BABCD
CBABC
DCBAB
EDCBAComplete PHP Program (5 Rows)
Fixed version (A–E):
<?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
Outer loop chooses the row anchor
$i goes from 0 to 4, so the row anchor letter goes A, B, C, D, E.
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.
Second inner loop fills the remaining width
The cap $k - $i decreases each row so the total letters per row stay at $k + 1.
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.
Put it together
The outer loop controls rows, the inner loops control what prints on each row, and PHP_EOL separates the lines.
Variation — User Input (CLI) Version
Clamps rows to 26 (A–Z):
<?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
PHP_EOL is correct for CLI output and keeps examples consistent for terminal execution. In HTML, you would use <br> instead.Next: PHP Alphabet Pattern 31
Continue to the next program for another alphabet pattern in PHP.
10 people found this page helpful
