Centered Palindromic Number Pyramid in PHP

What You’ll Learn
How to print a centered palindromic number pyramid in PHP using three nested loops.
You’ll combine leading spaces, ascending numbers, and descending numbers to form each row.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1Complete PHP Program
First print leading spaces, then ascending sequence, then descending mirror.
<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = 5; $j > $i; $j--) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
echo $k . " ";
}
$n = $k - 1;
for ($m = 1; $m < $i; $m++) {
echo --$n . " ";
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls rows
for ($i = 1; $i <= 5; $i++) sets the current row size.
Leading spaces
for ($j = 5; $j > $i; $j--) adds indentation to center the row.
Ascending then descending
Print 1..$i, then set $n = $k - 1 and print $n-1..1.
New line per row
echo PHP_EOL; prints each palindrome on a separate line.
Centered palindromic pyramid
Row widths grow by 2 each line, and total loop work is O(n²).
Variation — User Input (CLI) Version
This version accepts row count from user input (run from terminal with php):
<?php
echo "Enter number of rows: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $n; $j > $i; $j--) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
echo $k . " ";
}
$temp = $k - 1;
for ($m = 1; $m < $i; $m++) {
echo --$temp . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Swap numbers with letters to build alphabet palindromic pyramids
- Use fixed-width formatting for clean multi-digit alignment
- Create an inverted pyramid by reversing outer loop direction
- Add hollow-center logic to print only boundary values
- Parameterize spacing token for console vs web output
Avoid
- Mixing HTML-only empty div spacing in CLI examples
- Forgetting to reset descending counter each row
- Using wrong descending bound and duplicating middle value
- Skipping validation for invalid input rows
Key Takeaways
Three loops handle spaces, ascending values, and descending values.
Each row is a palindrome around its peak number.
Indentation controls pyramid centering.
Same design can be adapted to star, alphabet, and hollow pyramids.
❓ Frequently Asked Questions
$n = 7 in dynamic version; all loops adjust automatically.Explore More PHP Number Patterns!
Continue mastering centered and mirrored patterns with nested loops.
Palindromic pyramids are frequently used in programming interviews to assess loop control, indexing, and symmetry logic together.
12 people found this page helpful
