Palindromic Number Pyramid in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Increase + Decrease

What You’ll Learn

The palindromic number pyramid prints centered rows that read the same forwards and backwards. For $rows = 5: 1, 1 2 1, 1 2 3 2 1, and so on. Each row uses leading spaces, an increase loop 1..$i, and a decrease loop $i-1..1. This tutorial covers the three-part row logic, live preview, worked PHP examples, edge cases, and O(n²) complexity.

Leading Spaces

$j = $rows..$i

Echo $rows - $i + 1 pairs of spaces to center each row.

Increase Loop

$k = 1..$i

Echo numbers 1 through $i on the way up.

Decrease Loop

--$n

Set $n = $i, then echo --$n for $i-1 steps — mirrors without duplicating peak.

Palindromic Row

2i - 1 nums

Row i has 2i-1 numbers — increase half plus decrease half.

Live Preview

3–12 rows

Pick row count and draw the palindromic pyramid instantly in the browser.

O(n²)

Complexity

Each row prints O(n) spaces and numbers — total work grows as n².

Introduction

A palindromic number pyramid centers each row with leading spaces, then prints 1..i and i-1..1. Row 2 reads 1 2 1; row 3 reads 1 2 3 2 1.

In PHP: outer for ($i = 1; $i <= $rows; $i++), space loop $j = $rows..$i, increase loop $k = 1..$i, decrease loop with --$n, then echo PHP_EOL.

📝 Problem & Approach

Given $rows = 5, print five centered palindromic rows — widest row has 1 2 3 4 5 4 3 2 1.

PHP
// $rows = 5 (conceptual output — centered)
//         1 
//       1 2 1 
//     1 2 3 2 1 
//   1 2 3 4 3 2 1 
// 1 2 3 4 5 4 3 2 1 

Inputs & Outputs

ItemTypeDescription
$rowsintNumber of triangle rows (typically ≥ 1).
i, j, k, n, mintRow i; space index j; increase k; decrease n/m.
Printed outputtext2i-1 numbers per row when centered; palindromic sequence.

Minimal workflow

Pseudocode
for $i from 1 to $rows:
    echo ($rows-$i+1) space pairs
    echo 1..$i
    echo $i-1..1 using --$n
    echo PHP_EOL

Approach comparison

ApproachIdeaBest for
Three-part rowSpaces + increase loop + decrease loopCentered palindromic rows
implode rowBuild row without trailing spacesCleaner console output — Example 3
fgets(STDIN) input(int) $input for rowsUser-chosen row count
Compact outputimplode joins values with single spacesNo trailing space per row — Example 3

⚡ Quick Reference

GoalPattern
Set rows$rows = 5;
Outer loopfor ($i = 1; $i <= $rows; $i++)
Space loopfor ($j = $rows; $j >= $i; $j--) echo " "
Increase loopfor ($k = 1; $k <= $i; $k++) echo $k
Decrease loop$n = $i; echo --$n for $m = 1..$i-1
Row breakecho PHP_EOL; after all three parts
Program 55 contrastDiagonal-fill triangle uses step logic; this pyramid uses centered palindrome rows

📋 Spaces vs Increase vs Decrease

How leading spaces, increase loop, decrease loop, and row breaks work together.

Leading spaces
for ($j = $rows; $j >= $i; $j--)
echo "  "

Centers row $i in the pyramid.

Increase loop
for ($k = 1; $k <= $i; $k++)
echo $k . " "

Echoes 1 2 3 ... $i on row $i.

Decrease loop
$n = $i
for ($m = 1; $m < $i; $m++)
  echo --$n

Echoes $i-1 ... 1 — mirrors without repeating peak.

Learning tip
trace $i=3, $rows=5

Dry-run row 3: spaces + 1 2 3 + 2 1 → palindrome.

Context

When This Pattern Shows Up

Reach for this pattern when teaching centering, palindrome rows, and nested loops.

  1. First lab exercise

    Classic follow-up after diagonal-fill triangles — introduces centered palindromic rows.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible pattern size.

  4. Gateway to variants

    Compare with Program 55 (diagonal-fill triangle), then continue to Program 57 hollow pyramid.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one program that locks in centering, palindrome rows, and O(n²) thinking.

🔮 Live Preview

Choose pattern size n and draw the full palindromic number pyramid number pattern in the browser.

Try 3, 5, or 8 for rows (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed $rows = 5, fgets(STDIN) input, and a compact implode variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five centered palindromic rows — widest row has nine numbers.

Example 1 — Fixed $rows = 5

Hard-coded $rows = 5 — leading spaces, increase loop 1..$i, decrease loop with --$n.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $rows; $j >= $i; $j--) echo "  ";
    for ($k = 1; $k <= $i; $k++) echo $k . " ";

    $n = $i;
    for ($m = 1; $m < $i; $m++) echo --$n . " ";

    echo PHP_EOL;
}

How It Works

Row 1 prints one centered 1. Row 3 prints spaces, then 1 2 3, then 2 1 — a palindrome.

📈 Practical Variant

Read $rows with fgets(STDIN) for flexible output size.

Example 2 — fgets(STDIN) Input

Same palindromic row logic; row count comes from user input.

PHP
<?php
echo "Enter rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $rows; $j >= $i; $j--) echo "  ";
    for ($k = 1; $k <= $i; $k++) echo $k . " ";
    $n = $i;
    for ($m = 1; $m < $i; $m++) echo --$n . " ";
    echo PHP_EOL;
}

How It Works

Same palindromic row logic as Example 1; row count comes from fgets(STDIN) input.

⚡ Compact Variant

Build each row with an array and implode — no trailing space.

Example 3 — Compact Rows

Same logic; use an array and implode to join values without a trailing space.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    $spaces = str_repeat("  ", $rows - $i + 1);
    $parts = [];
    for ($k = 1; $k <= $i; $k++) $parts[] = $k;
    $n = $i;
    for ($m = 1; $m < $i; $m++) $parts[] = --$n;
    echo $spaces . implode(" ", $parts) . PHP_EOL;
}

How It Works

Same palindromic logic; implode on an array produces clean rows without trailing spaces.

🧠 How the Algorithm Builds Each Row

1

Set up & outer loop

Set $rows (e.g. 5). Outer loop for ($i = 1; $i <= $rows; $i++) builds one centered row per iteration.

Setup
2

Print leading spaces

for ($j = $rows; $j >= $i; $j--) echoes " " to center row $i.

Spaces
3

Print increasing half

for ($k = 1; $k <= $i; $k++) echoes 1 2 3 ... $i.

Increase
4

Print decreasing half

$n = $i, then echo --$n for $m = 1..$i-1; then echo PHP_EOL.

Break
=

Palindromic number pyramid complete

Total numbers = (e.g. 25 for $rows=5) — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — row $i = 3, $rows = 5

Trace row 3 to see spaces, increase half, and decrease half form 1 2 3 2 1.

PhaseLoopRow so far
Spacesj=5..3    
Increasek=1..3    1 2 3
Decreasem=1,2 → --n    1 2 3 2 1

Final centered row 3: 1 2 3 2 1. Then echo PHP_EOL moves to row 4.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Increase + Decrease

Clearest visual proof that outer and inner bounds interact.

Example: use fgets(STDIN) for dynamic rows — see Example 2.

2. Leading Space Padding

Each row echoes $rows - $i + 1 pairs of spaces before numbers.

Example: trace row 3 with rows=5 — 2 space pairs before digits.

3. Console Formatting Drills

Practice echo PHP_EOL vs echo for multi-line vs same-line output.

Example: use implode for clean rows — see Example 3.

4. Palindrome Check

Each row reads the same forwards and backwards — peak digit appears once.

Example: row 4 reads 1 2 3 4 3 2 1 when centered.

5. Complexity Intuition

Each row prints O(n) spaces and numbers — total work grows as n².

Example: count numbers on row 5 → 2×5-1 = 9 digits per row.

6. Input Validation Labs

Pair the pattern with fgets(STDIN) and positive-row checks.

Example: reject $rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner loop roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner PHP courses.

  1. 1. Instant Visual Feedback

    Missing decrease loop shows immediately — rows are not palindromic.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Change rows, use fgets(STDIN), or build rows with implode.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-part row (spaces, up, down) first; then try fgets(STDIN) input and the implode variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use $rows for height and $i/$j/$k/$n for loop variables.

  2. 2. Prefer fgets(STDIN)

    Avoid crashes when the user types letters instead of a number.

  3. 3. Row Break After Inner Loop

    Finish the inner loops for row $i, then call echo PHP_EOL.

  4. 4. Use --n for Decrease

    Set $n = $i before the decrease loop; echo --$n exactly $i-1 times.

  5. 5. Dry-Run One Small Row Count

    Trace $rows = 5, $i = 3 on paper — expect centered 1 2 3 2 1.

Pro Tip: if the peak digit prints twice, check whether the decrease loop uses $m < $i.

Common Pitfalls

Mistakes that commonly break palindromic number pyramid number patterns.

  1. 1. echo PHP_EOL Inside an Inner Loop

    Each number lands on its own line — you get a vertical stack, not a centered pyramid row.

    → Use echo inside space, increase, and decrease loops; echo PHP_EOL only after they finish.

  2. 2. Forgetting the Decrease Loop

    Without --$n, rows echo only 1..$i — no palindrome.

    → Add the decrease loop: $n = $i, then echo --$n for $m = 1..$i-1.

  3. 3. Forgetting the Row Break

    Omitting echo PHP_EOL after the three inner loops glues all rows onto one line.

    → Always call echo PHP_EOL after space, increase, and decrease loops complete.

  4. 4. Decrease Loop Uses i Instead of i-1

    Looping m = 1..i duplicates the peak digit — row 3 becomes 1 2 3 3 2 1.

    → Use m < i so exactly i-1 descending digits print.

  5. 5. Unchecked fgets(STDIN) Input

    Letters or empty input throw invalid input without validation.

    → Use is_numeric($input) before (int) $input.

  6. 6. Hard-coding 5 Everywhere

    Using literal 5 in loop bounds instead of variable $rows breaks dynamic input.

    → Use one $rows variable for outer loop and space/number bounds.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single line

Output is one centered line: 1 — the decrease loop does not run.

rows = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

$rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large rows

Large rows

Large values produce wide rows — fine for labs; use smaller n for quick demos.

Bad input

Non-numeric fgets(STDIN) input

Unchecked fgets(STDIN) input leaves $rows unset — call is_numeric($input) first.

Compact

Single-line form

Use conditional spacing to avoid trailing spaces — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change $rows

  • Try $rows = 3, 6, or 8
  • Verify row i reads the same forwards and backwards

2. implode rows

  • Build each row without trailing spaces
  • Compare print-based vs implode output

3. Skip decrease loop

  • Omit the --n loop and see non-palindromic rows
  • Observe missing symmetry

4. Next in series

  • Continue with Program 57 hollow pyramid
  • Try rows=6 and verify row 6 reads 1 2 3 4 5 6 5 4 3 2 1

Notes

  • Cell count. Row $i has 2*$i-1 numbers; total = (e.g. 25 numbers for $rows=5).
  • echo stays on the line; echo PHP_EOL advances — mix them carefully.
  • Validate $rows > 0 for interactive programs; $rows = 1 prints one number.
  • Row logic: spaces, then 1..i, then --n for i-1 steps.

Quick Takeaway: outer $i=1..$rows; spaces; echo 1..$i; echo --$n; then echo PHP_EOL.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed $rows = 5 (Example 1)O(n²)O(1)
fgets(STDIN) input (Example 2)O(n²)O(1)
Compact rows (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The palindromic number pyramid combines centering with increase/decrease loops — a natural step after diagonal-fill triangle patterns. Master the fixed-$rows version first, then try fgets(STDIN) input and the compact implode variant in Example 3.

Practice the three examples above, then continue to Program 57 for the hollow number pyramid pattern.

Print leading spaces before numbers on every row — one echo PHP_EOL per outer iteration.

💡 Best Practices

✅ Do

  • Explain outer i, space loop, increase loop, and decrease loop before coding
  • Echo spaces, then 1..$i, then --$n; then echo PHP_EOL
  • Validate $rows ≥ 1 for interactive programs
  • Check fgets(STDIN) return value before using $rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Forget the decrease loop
  • Use m <= i in decrease loop (duplicates peak)
  • Hard-code 5 instead of variable $rows
  • Ignore bad console input in user-facing demos
  • Skip the $rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this palindromic number pyramid pattern

Center each row with spaces, then echo increase and decrease halves.

5
Core concepts
02

Outer loop

$i = 1..$rows

Code
03

Palindromic halves

Echo 1..$i then --$n

Logic
n 04

Row length

2*$i-1 nums/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Each row reads the same forwards and backwards — e.g. 1 2 3 2 1. Leading spaces center the pyramid shape.
Row 2 prints increasing 1 2, then decreasing 1 using the --$n loop — forming a palindrome.
One loop prints 1..$i, another prints $i-1..1 with --$n. Together they mirror the row without duplicating the peak.
Yes. Use a variable $rows in all loop bounds and space padding.
2*$i - 1 numbers — $i ascending plus $i-1 descending.
Collect numbers in an array and echo implode(' ', $parts) after the leading spaces — see Example 3.
O(n²) for n rows because each row prints O(n) spaces and numbers.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you Know? 🔊

Each row is palindromic: print leading spaces, numbers 1..$i, then $i-1..1. Row 3 reads 1 2 3 2 1 when centered.

Continue to Program 57

Move on to the hollow number pyramid pattern in the PHP number-pattern series.

Program 57 tutorial →

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.

12 people found this page helpful