Palindrome Number Triangle in PHP

What You’ll Learn
How to print a palindrome number triangle in PHP:
1, 121, 12321, 1234321, 123454321.
The idea is simple: print numbers increasing from 1 to $i, then print them back down from $i-1 to 1.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
121
12321
1234321
123454321Complete PHP Program
First we print 1..$i, then we print $i-1..1 to mirror the row.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
for ($k = $i - 1; $k >= 1; $k--) {
echo $k;
}
echo PHP_EOL;
}🧠 How It Works
Choose the row count
$rows = 5; sets how many palindrome rows to print.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) controls the row length and the peak digit.
Left side: print 1..i
The first inner loop prints 1 through $i.
Right side: print i-1..1
The second inner loop prints back down from $i-1 to 1, completing the palindrome.
Palindrome rows
Each row is symmetric because the right side is the reverse of the left side (without repeating the peak).
Variation — User Input (CLI) Version
Let the user decide the number of rows at runtime using standard input (run from terminal with php):
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
for ($k = $i - 1; $k >= 1; $k--) {
echo $k;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for readability when
$rowsis large - Center-align the triangle by printing leading spaces before each row
- Print the descending version by iterating
$ifrom$rowsdown to 1 - Use
printfpadding to align multi-digit numbers - Swap digits for characters to build alphabet palindromes
Avoid
- Starting the mirror loop at
$i(it will repeat the peak number) - Forgetting the newline after each row
- Mixing row/column logic in nested loops
- Skipping input validation in CLI mode
Key Takeaways
Print 1..i to build the left half of the row.
Print i-1..1 to mirror without duplicating the peak.
The outer loop controls the peak digit and the number of rows.
This pattern is a classic example of building symmetric output with loops.
❓ Frequently Asked Questions
$i - 1. That prints the reverse without duplicating the peak digit.$i increases.Explore More PHP Number Patterns!
Palindrome patterns are a great stepping stone to diamonds and centered pyramids.
Palindromes show up everywhere in coding interviews—this pattern is a visual way to practice the same mirroring idea.
12 people found this page helpful
