PHP Square Number Pyramid Pattern

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

What Is This Pattern?

A square-numbers pyramid prints consecutive perfect squares in centered rows whose widths are odd: 1, then 3, then 5, and so on.

Remember
Rule: odd row widths; print next m² with width 4

                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625   ← 5 levels

In PHP use $maxWidth = 2 * $levels - 1. The outer loop steps $i by 2; indent with spaces, then print $i squares from a running counter $m.

How to Solve It

One odd-step outer loop with indent, then a continuous square counter.

MethodIdeaBest for
Centered pyramidIndent, then print $m*$m with %4dLearning, interviews, exams
Levels inputSame logic with $maxWidth = 2*$levels - 1Practice / demos

Pseudocode

Pseudocode
maxWidth = 2 * levels - 1
m = 1
for i from 1 to maxWidth step 2:
    for j from i to maxWidth-1:
        print two spaces
    repeat i times:
        print m*m (width 4), then m = m + 1
    print newline

Cheat sheet

GoalPattern
Odd row widthsfor ($i = 1; $i <= $maxWidth; $i += 2)
Center the rowfor ($j = $i; $j < $maxWidth; $j++) echo " ";
Next squareprintf("%4d", $m * $m); $m++;
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo " " / printf("%4d", ...)Stays on the same lineEach indent or square
echo PHP_EOLEnds the current lineAfter both inner loops

Print indents and squares without a newline, then end the row once.

Live Preview

Change the level count and the square pyramid updates instantly.

Whole numbers from 1 to 5 (keeps width-4 columns readable). Tap a chip or type a value — the preview redraws as you go.

Live result 5 levels · 25 squares
                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625

Worked Walkthrough — $levels = 3

$maxWidth = 5. Trace indents and the running square counter.

$iIndent / squaresPrinted row
14 pads / 11
32 pads / 4 9 164 9 16
5none / 25..8125 36 49 64 81

Total squares for n levels = n². Counter $m never resets between rows.

PHP Programs

Three complete programs: fixed 5 levels, CLI input levels, and a compact 3-level demo. Use View Output for sample results.

Example 1 — Fixed $levels = 5 ($maxWidth = 9)

Odd-step outer loop: indent, then print consecutive $m*$m values with width 4.

PHP
<?php
$m = 1;

for ($i = 1; $i <= 9; $i += 2) {
    for ($j = $i; $j < 9; $j++)
        echo "  ";

    for ($k = 1; $k <= $i; $k++) {
        printf("%4d", $m * $m);
        $m++;
    }

    echo PHP_EOL;
}

How It Works

1. Odd widths. $i takes 1, 3, 5, 7, 9 — that many squares print on each row.

2. Indent. Print " " while $j runs from $i to just below 9 so narrow rows stay centered.

3. Squares. Print $m*$m with printf("%4d", ...), then increment $m — never reset between rows.

Example 2 — User Input (levels)

Read the level count from STDIN and set $maxWidth = 2 * $levels - 1.

PHP
<?php
echo "Enter levels: ";
$input = trim(fgets(STDIN));

if (!is_numeric($input) || (int) $input < 1) {
    echo "Please enter a positive whole number." . PHP_EOL;
    exit(1);
}

$levels = (int) $input;
$maxWidth = 2 * $levels - 1;
$m = 1;

for ($i = 1; $i <= $maxWidth; $i += 2) {
    for ($j = $i; $j < $maxWidth; $j++)
        echo "  ";

    for ($k = 1; $k <= $i; $k++) {
        printf("%4d", $m * $m);
        $m++;
    }

    echo PHP_EOL;
}

How It Works

1. Validate levels. Check is_numeric; require $levels >= 1.

2. Same pyramid. Three levels end at 81 with nine squares total.

Example 3 — Compact $levels = 3

A smaller fixed demo — same centered idea, easier to trace by hand.

PHP
<?php
$levels = 3;
$maxWidth = 2 * $levels - 1;
$m = 1;

for ($i = 1; $i <= $maxWidth; $i += 2) {
    for ($j = $i; $j < $maxWidth; $j++)
        echo "  ";

    for ($k = 1; $k <= $i; $k++) {
        printf("%4d", $m * $m);
        $m++;
    }

    echo PHP_EOL;
}

How It Works

1. Same rules. Odd $i sets count; indent; print the next squares.

2. Quick check. The base row has five values: 25 through 81.

Edge Cases & Pitfalls

Check these before calling the solution done.

reset $m

Reset $m = 1 each row

That reprints 1, 4, 9 on every line. Keep $m outside the outer loop.

$i++

Use $i++ instead of $i += 2

Row widths become 1, 2, 3… instead of odd lengths. Keep the step of 2.

no format

Print $m*$m without width

Columns drift once values hit three digits. Prefer printf("%4d", $m * $m).

levels = 1

Single 1

Output is just the formatted 1 — one level, one square.

levels ≤ 0

Empty output

The outer loop never runs. Validate and prompt again for clearer UX.

Bad input

(int) alone is not enough

Prefer is_numeric after trim(fgets(STDIN)) so non-numeric input does not silently become 0.

Time and Space Complexity

ProgramTimeExtra space
Fixed / compact (Examples 1, 3)O(n²)O(1)
User input (Example 2)O(n²)O(1)

Total printed squares are 1 + 3 + 5 + … + (2n-1) = n², so work is quadratic in the level count.

Key Takeaways

  • Rule: odd row widths via $i += 2; each cell prints the next $m*$m.
  • Center: indent with " " before printing; use %4d for column alignment.
  • echo vs PHP_EOL: indents and squares stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 42 prints a hollow square border of 1s.

One line: for each odd width, indent then print the next perfect squares from a shared counter.

Frequently Asked Questions

A centered pyramid of perfect squares: row 1 prints 1 (1²), row 2 prints 4 9 16 (2², 3², 4²), and so on.
The outer loop increases $i by 2 each time ($i += 2), so $i takes odd values — each becomes the count of squares printed on that row.
An indentation loop prints spaces before each row. As $i grows, fewer spaces are printed, so wider rows shift left and stay centered.
$m starts at 1 and increments after every printed square. Each value printed is $m*$m — the next perfect square in sequence.
Fixed-width columns keep the pyramid aligned as squares grow from 1 to 625. Without it, columns drift apart.
Increase levels so $maxWidth = 2*$levels - 1 grows — see Example 2.
Program 40 alternates 1 and 0 with shrinking rows. Program 41 prints perfect squares in a centered pyramid with growing odd-width rows.
O(n²) for n levels — total prints are 1+3+5+...+(2n-1) = n².
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.

Did you know?

Each printed value is $m² from a running counter $m. Row widths are odd (1, 3, 5, 7, 9) — total prints for n levels = n².

Next: Hollow Square Border of 1s

Print a square frame of 1s with empty space inside.

Program 42 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.

6 people found this page helpful