PHP Number Pyramid Pattern (Centered Continuous)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A centered continuous number pyramid prints odd-width rows with leading spaces, while a single counter $k keeps rising across every row.

Remember
Rule: for odd i up to max,
      reverse-scan columns — space when j > i, else print k++

    1
  2 3 4
5 6 7 8 9     ← max = 5

Unlike Program 20 (left-aligned continuous triangle), this version centers each row with a reverse inner loop and an if ($j > $i) space check. Program 25 continues with a bidirectional number triangle.

How to Solve It

Odd outer widths, reverse inner scan, shared counter $k. End each row with echo PHP_EOL.

MethodIdeaBest for
Reverse + ifScan $j from $max down; space when $j > $i, else $k++Learning, interviews, exams
Safe inputSame loops; re-prompt until is_numeric succeedsConsole apps that must reject bad input

Pseudocode

Pseudocode
k = 1
for i from 1 to max step 2:
    for j from max down to 1:
        if j > i:
            print space
        else:
            print k and a space
            k = k + 1
    print newline

Cheat sheet

GoalPattern
Odd row widthsfor ($i = 1; $i <= $max; $i += 2)
Start counter once$k = 1; before the outer loop
Reverse columnsfor ($j = $max; $j >= 1; $j--)
Space vs numberif ($j > $i) echo " "; else echo $k++ . " ";
End the rowecho PHP_EOL;
Even max fixif ($max % 2 == 0) $max -= 1;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo " " / echo $k++ . " "Stays on the same lineLeading spaces and each number
echo PHP_EOLEnds the current lineAfter the inner loop

Print spaces and numbers without a newline, then end the row once.

Live Preview

Change the max odd width and the centered pyramid updates instantly. Even values are adjusted down by 1.

Odd whole numbers from 1 to 9 (single digits). Even values are adjusted down by 1.

Live result max = 5 · 3 rows · 9 numbers
    1 
  2 3 4 
5 6 7 8 9 

Worked Walkthrough

Trace $max = 5 — leading spaces, printed numbers, and $k after each row.

$iLeading spacesNumbers$k afterPrinted row
14 ($j = 5..2)121
32 ($j = 5..4)2 3 452 3 4
505 6 7 8 9105 6 7 8 9

Each row scans all $max columns — total work is O(n²) for width n.

PHP Programs

Three complete programs: fixed max, CLI input with even-width fix, and a safe re-prompt loop. Use View Output for sample results.

Example 1 — Fixed $max = 5

Hard-coded width — reverse inner loop centers each row; $k never resets.

PHP
<?php
$max = 5;
$k = 1;

for ($i = 1; $i <= $max; $i += 2) {
    for ($j = $max; $j >= 1; $j--) {
        if ($j > $i) {
            echo " ";
        } else {
            echo $k++ . " ";
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Odd widths. $i += 2 walks 1, 3, 5 — each value is how many numbers that row prints.

2. Reverse scan. $j runs from $max down to 1. While $j > $i, print a leading space.

3. Shared counter. Otherwise print $k++. $k sits outside the outer loop, so values continue across rows.

Example 2 — User Input

Read $max from the CLI; adjust even widths down by 1.

PHP
<?php
echo "Enter the maximum odd width: ";
$max = (int) trim(fgets(STDIN));

if ($max % 2 == 0) {
    $max -= 1;
}

$k = 1;
for ($i = 1; $i <= $max; $i += 2) {
    for ($j = $max; $j >= 1; $j--) {
        if ($j > $i) {
            echo " ";
        } else {
            echo $k++ . " ";
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Read max. Ask for a max width, then trim(fgets(STDIN)) and cast to int.

2. Keep it odd. If the user types 6, subtract 1 so the last row width is still 5.

3. Same pyramid core. After the fix, the reverse-loop + $k++ logic matches Example 1.

Example 3 — Safe Input Loop

Re-prompt until a positive whole number arrives, then draw the pyramid.

PHP
<?php
$max = 0;

echo "Enter the maximum odd width: ";
while ($max < 1) {
    $input = trim(fgets(STDIN));
    if (is_numeric($input) && (int) $input >= 1) {
        $max = (int) $input;
    } else {
        echo "Please enter a positive whole number: ";
    }
}

if ($max % 2 == 0) {
    $max -= 1;
}

$k = 1;
for ($i = 1; $i <= $max; $i += 2) {
    for ($j = $max; $j >= 1; $j--) {
        if ($j > $i) {
            echo " ";
        } else {
            echo $k++ . " ";
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Validate in a loop. Stay in while ($max < 1) until a positive int arrives.

2. Reject bad tokens. Non-numeric input re-prompts instead of casting to 0 silently.

3. Then draw. After validation (and the even-width fix), the same reverse-loop pyramid runs.

Edge Cases & Pitfalls

Check these before calling the solution done.

k inside

Resetting $k each row

Declaring $k inside the outer loop restarts at 1 every row. Keep $k before the loops.

i++

Using $i++ instead of $i += 2

That prints every length. Use $i += 2 for the odd pyramid shape.

forward j

Scanning $j upward

That puts spaces after numbers. The reverse scan ($j from $max down) puts spaces on the left.

PHP_EOL inside

echo PHP_EOL inside the inner loop

That breaks the row. Call echo PHP_EOL only after the column scan finishes.

max = 1

Single number

Output is 1 — a good sanity check.

even max

Even width without a fix

Subtract 1 (or prompt again) so the last row still has an odd width.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input / safe (Examples 1–3)O(n²)O(1)

There are about n/2 rows, and each row scans all n columns, so total work is O(n²).

Key Takeaways

  • Rule: for each odd $i, reverse-scan columns — space when $j > $i, else print $k++.
  • Scope: keep $k outside the outer loop so the sequence never restarts.
  • echo vs PHP_EOL: spaces and numbers stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 25 prints a bidirectional number triangle.

One line: for odd $i, reverse-scan — space when $j > $i, else echo $k++ . " ", then echo PHP_EOL.

Frequently Asked Questions

The program prints leading spaces when $j > $i, which shifts the numbers to the right and centers the pyramid.
Because the counter $k is not reset inside the outer loop. It increments with $k++ each time a number is printed.
Row widths are odd (1, 3, 5, …) so each row adds two more numbers than the previous row.
echo " " stays on the same line for spaces and numbers. echo PHP_EOL ends the current row after the inner loop finishes.
The reverse inner loop lets you print leading spaces first (when $j > $i) and numbers afterward — a common centering trick.
Subtract 1 to force an odd width, or validate and prompt again. This version assumes odd row sizes.
O(n²) for max width n because each row iterates across n columns.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 3 for a re-prompt loop.
Only one row prints — a single centered 1 (no leading spaces when max is 1).

Did you know?

This centered pyramid prints numbers continuously using a counter $k. An if inside a reverse loop prints leading spaces when $j > $i, then prints $k++ once the column reaches the row boundary.

Next: Bidirectional Number Triangle

Continue with rows that count both ways on the same line.

Program 25 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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