PHP Hollow Square Number Pattern (Border)

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

What Is This Pattern?

A hollow square border fills only the frame of an n×n grid with consecutive numbers — top left-to-right, right top-to-bottom, bottom right-to-left, left bottom-to-top. Interior cells stay blank.

Remember
Rule: for each cell (i, j) in size×size
        if top:    print j
        elif right: print k++
        elif bottom: print l--
        elif left:  print m--
        else:       print spaces

1  2  3  4  5
16          6
15          7
14          8
13 12 11 10 9     ← size = 5

Unlike Program 58 (hollow diamond edges), here you scan a full square and decide border vs interior per cell. Program 60 continues by trimming the last digit each line.

How to Solve It

Nested loops visit every cell. An if/elseif chain picks the correct edge counter. Use printf("%-3d", …) so two-digit values stay aligned. End each row with echo PHP_EOL.

MethodIdeaBest for
Fixed sizeHard-code 5×5; counters $k/$l/$mLabs and demos
CLI inputSame edges; compute counters from $sizeAny square size
Simple borderOne counter on border cellsEasier logic (different sequence)

Pseudocode

Pseudocode
k = size + 1
l = 3 * size - 2
m = 4 * size - 4

for i from 1 to size:
    for j from 1 to size:
        if i == 1:          print j
        else if j == size:  print k; k = k + 1
        else if i == size:  print l; l = l - 1
        else if j == 1:     print m; m = m - 1
        else:               print spaces
    print newline

Cheat sheet

GoalPattern
Set size$size = 5;
Init counters$k = $size + 1; $l = 3 * $size - 2; $m = 4 * $size - 4;
Top edgeif ($i == 1) printf("%-3d", $j);
Right / bottom / left$k++ / $l-- / $m-- with printf
Interiorecho " "; (three spaces)
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
printf("%-3d", …) / echo " "Stays on the same lineEach cell (number or spaces)
echo PHP_EOLEnds the current lineAfter the inner loop finishes

Build the full row cell by cell, then break once.

Live Preview

Change the square size and the hollow border updates instantly (Examples 1–2 sequence).

Whole numbers from 3 to 8. Tap a chip or type a value — the preview redraws as you go.

Live result size = 5 · cells = 25
1  2  3  4  5  
16          6  
15          7  
14          8  
13 12 11 10 9  

Worked Walkthrough

Trace $size = 5 — how each edge gets its numbers (corners belong to the first matching branch).

EdgeConditionValues
Top$i == 11 2 3 4 5
Right$j == 5 (not top)6 7 8 9
Bottom$i == 5 (not right)13 12 11 10
Left$j == 1 (middle rows)16 15 14

Order of if / elseif matters: the bottom-right corner is taken by the right-edge branch (9), not by $l--.

PHP Programs

Three complete programs: fixed 5×5, CLI $size, and a simpler sequential-border variant. Use View Output for sample results.

Example 1 — Fixed $size = 5

Hard-coded 5×5 — counters $k = 6, $l = 13, $m = 16 with %-3d formatting.

PHP
<?php
$k = 6;
$l = 13;
$m = 16;

for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        if ($i == 1)
            printf("%-3d", $j);
        elseif ($j == 5)
            printf("%-3d", $k++);
        elseif ($i == 5)
            printf("%-3d", $l--);
        elseif ($j == 1)
            printf("%-3d", $m--);
        else
            echo "   ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Top. When $i == 1, print column index $j — values 1..5.

2. Right, bottom, left. $k++ fills the right edge; $l-- walks the bottom leftward; $m-- walks the left edge upward.

3. Interior. Non-border cells print three spaces so columns stay lined up with %-3d.

Example 2 — User Input

Read $size from the CLI and compute $k, $l, $m from formulas.

PHP
<?php
echo "Enter size: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 2) {
    echo "Enter a whole number >= 2." . PHP_EOL;
    exit(1);
}
$size = (int) $input;

$k = $size + 1;
$l = 3 * $size - 2;
$m = 4 * $size - 4;

for ($i = 1; $i <= $size; $i++) {
    for ($j = 1; $j <= $size; $j++) {
        if ($i == 1)
            printf("%-3d", $j);
        elseif ($j == $size)
            printf("%-3d", $k++);
        elseif ($i == $size)
            printf("%-3d", $l--);
        elseif ($j == 1)
            printf("%-3d", $m--);
        else
            echo "   ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Validate input. is_numeric rejects letters; require size at least 2.

2. Scale counters. $k = $size + 1, $l = 3*$size - 2, $m = 4*$size - 4 match the clockwise sequence for any $size.

3. Same edges. The if/elseif chain matches Example 1 — only bounds and counters change.

Example 3 — Simple Sequential Border

One counter on every border cell — easier code, different (row-major) numbering.

PHP
<?php
$size = 5;
$val = 1;

for ($i = 1; $i <= $size; $i++) {
    for ($j = 1; $j <= $size; $j++) {
        $border = ($i == 1 || $i == $size || $j == 1 || $j == $size);
        if ($border)
            printf("%-3d", $val++);
        else
            echo "   ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Border test. A cell is on the frame when row or column is first or last.

2. One counter. $val++ assigns the next number whenever $border is true.

3. Different sequence. Numbers follow scan order, not a continuous clockwise walk like Examples 1–2.

Edge Cases & Pitfalls

Check these before calling the solution done.

branch order

Testing bottom before right

Corners match multiple edges. Keep the order top → right → bottom → left so the bottom-right corner uses $k++.

wrong pad

Interior spaces not matching %-3d

Use exactly three spaces (" ") or columns drift when numbers hit two digits.

PHP_EOL inside

echo PHP_EOL inside the inner loop

That prints one cell per line. Call echo PHP_EOL only after the column loop finishes.

size = 2

Tiny square

All four cells are border — no interior spaces. Still a valid hollow frame.

size ≤ 1

Too small

Reject or special-case. A 1×1 grid is just 1; size 0 prints nothing.

wrong formulas

Hard-coding $k/$l/$m for other sizes

Values 6/13/16 are only for size 5. Use the formulas in Example 2 when $size changes.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Simple border (Example 3)O(n²)O(1)

There are n² cells, and each is visited once, so total work is O(n²). Only a few counters use extra memory.

Key Takeaways

  • Rule: print numbers on the frame only — top, right, bottom, left — spaces inside.
  • Branch order: top → right → bottom → left so corners are not double-handled.
  • printf vs PHP_EOL: each cell stays on the line; echo PHP_EOL advances after the row.
  • Next step: Program 60 prints a number, then drops its last digit on each following line.

One line: walk the square border with edge counters; leave the interior blank.

Frequently Asked Questions

Numbers only on the border of a square grid — interior cells are spaces creating a hollow frame.
Each edge continues the sequence differently: $k increments on the right, $l and $m decrement on bottom and left edges.
Fixed-width formatting keeps columns aligned when numbers reach two digits.
Yes. Generalize with $k=$size+1, $l=3*$size-2, $m=4*$size-4 — see Example 2.
Example 3 uses a simple border check and one counter — easier but a different number sequence (row-major).
Non-border cells print three spaces — that creates the hollow interior.
printf/echo stay on the same line for each cell. echo PHP_EOL ends the row after the inner loop.
O(n²) for an n×n grid because every cell is visited once.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you know?

Numbers print only on the border of a 5×5 grid: top row 1..5, right column 6..9, bottom row 13..9, left column 16..14 — interior cells are spaces.

Next: Remove Last Digit Each Line

Continue with a pattern that shortens the number on every row.

Program 60 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