Spiral Border Number Square in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Nested Loops + State

What You’ll Learn

How to fill a 5×5 border with numbers using row/column rules and three running counters ($k, $l, $m).

You’ll see why elseif order matters at corners and how padding keeps columns aligned in plain text.

⭐ Pattern Output

For a 5×5 grid, the pattern looks like this (columns padded for alignment):

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

Complete PHP Program

Counters start at k = 6, l = 13, m = 16. Each cell prints a padded token so the border lines up in the terminal.

PHP
<?php
$k = 6;
$l = 13;
$m = 16;
$n = 5;
$w = 4;

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        $cell = '';
        if ($i == 1) {
            $cell = (string) $j;
        } elseif ($j == $n) {
            $cell = (string) $k++;
        } elseif ($i == $n) {
            $cell = (string) $l--;
        } elseif ($j == 1) {
            $cell = (string) $m--;
        }
        echo str_pad($cell, $w);
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Grid loops

$i and $j walk every cell from (1,1) to (n,n).

Scan
2

Top row rule

if ($i == 1) prints the column number 1..n.

First row
3

Right, bottom, left edges

Next checks: $j == $n uses $k++; $i == $n uses $l--; $j == 1 uses $m--.

Counters
4

Interior and padding

If no rule matches, $cell stays empty. str_pad(..., $w) keeps fixed column width for readable CLI output.

Alignment
=

Closed border

Numbers run along the perimeter; the center stays blank. Total work is O(n²).

2

Variation — User Input (CLI) Version

Reads grid size n. Starter values follow the same 5×5 recipe generalized: k = n + 1, m = 4n - 4, l = n² - 3(n - 1) (verified for n = 5; adjust if you change the walk).

PHP
<?php
echo "Enter grid size n: ";
$n = (int) trim(fgets(STDIN));

if ($n < 1) {
    echo "n must be at least 1" . PHP_EOL;
    exit;
}

$k = $n + 1;
$l = $n * $n - 3 * ($n - 1);
$m = 4 * $n - 4;
$w = max(2, strlen((string) ($n * $n)));

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        $cell = '';
        if ($i == 1) {
            $cell = (string) $j;
        } elseif ($j == $n) {
            $cell = (string) $k++;
        } elseif ($i == $n) {
            $cell = (string) $l--;
        } elseif ($j == 1) {
            $cell = (string) $m--;
        }
        echo str_pad($cell, $w);
    }
    echo PHP_EOL;
}

💡 Tips for Enhancement

Try These

  • Fill the full spiral inward layer by layer
  • Draw the same border with * for walls and digits on edges only
  • Log k, l, m after each row to verify counter flow
  • Swap elseif order on purpose to see which corners change
  • Use sprintf('%*d', $w, $val) for right-aligned numeric columns

Avoid

  • Reordering elseif blindly (corners depend on it)
  • Reusing the same 5×5 starter constants for arbitrary n without re-deriving them
  • Printing HTML <div> wrappers in CLI-focused lessons
  • Forgetting padding so multi-digit rows become hard to read

Key Takeaways

1

Border patterns often combine fixed edges with a few incrementing or decrementing counters.

2

elseif chain order defines which rule wins at overlapping corners.

3

Padding with str_pad keeps grid output readable without HTML layout.

4

For new sizes, recompute starter values or switch to a layer-by-layer spiral algorithm.

❓ Frequently Asked Questions

The j == n check appears before i == n, so the bottom-right corner is treated as part of the right column walk and prints $k++.
They match this tutorial’s 5×5 border walk. For other sizes, re-derive k, l, and m from the intended perimeter sequence or use a generic spiral fill.
Yes. Numbers will still be correct, but columns may not align in a monospace terminal.
O(n²) for an n×n grid.

Explore More PHP Number Patterns!

Level up from fixed borders to full matrix spirals and layered rectangles.

All Number Patterns →
Did you know?

Matrix spiral problems often appear in interviews; starting with an explicit border walk like this builds intuition before compact layer-stripping solutions.

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