Alphabet Pattern (A to ABCDE) in PHP

What You'll Learn
This PHP program prints a simple alphabet pattern where each row starts at A and grows by one letter.
For n rows, the total printed letters are 1 + 2 + … + n = n(n + 1)/2.
⭐ Pattern Output
When you run the program with rows = 5:
A
AB
ABC
ABCD
ABCDEComplete PHP Program
Fixed rows = 5 version:
<?php
$rows = 5;
$alpha = range('A', 'Z');
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}🧠 How It Works
Build an alphabet array
$alpha = range('A', 'Z'); creates an array with letters A to Z, so you can index letters like $alpha[0] = A, $alpha[1] = B, and so on.
Outer loop: one row per $i
for ($i = 0; $i < $rows; $i++) runs once per row. Row $i prints $i + 1 letters.
Inner loop: print A to the row end
for ($j = 0; $j <= $i; $j++) prints letters from $alpha[0] up to $alpha[$i]. Each echo appends a letter on the same line.
Growing alphabet rows
Total printed letters are n(n + 1)/2 for n rows — O(n²) time and O(1) extra space (besides the alphabet array).
Variation — User Input (CLI) Version
Read rows from standard input (works when you run the file from terminal using 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');
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j <= $i; $j++) {
echo $alpha[$j];
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print lowercase letters by using
range('a', 'z') - Start from another letter (e.g.,
'C') and adjust indexing - Reverse each row (ABCDE to A) for another variation
- Add spaces between letters for readability
- Try a centered alphabet pyramid next
Avoid
- Allowing
$rows > 26without handling wrap-around - Mixing HTML line breaks (
<br>) with CLI output unintentionally - Forgetting the newline after each row
- Using magic numbers like
65when'A'is clearer
Key Takeaways
Use nested loops: the outer loop controls rows and the inner loop prints letters.
Row i prints letters from A to the i-th letter (so each row grows by one).
Total printed letters are \(n(n+1)/2\), so runtime is O(n²).
range('A','Z') provides a clean and readable way to map indices to letters.
Clamp user input to 26 rows to stay within A to Z.
❓ Frequently Asked Questions
range('a', 'z') and the same loops.n rows, because the program prints 1+2+…+n letters in total.Next: PHP Alphabet Pattern 2
Continue to Program 2 for the next alphabet pattern in PHP.
In PHP, range('A','Z') returns an array of letters, which makes pattern problems easy to express without manual ASCII arithmetic.
10 people found this page helpful
