10×10 Perfect Square Spiral in PHP

Intermediate
⏱️ 8 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
2D Array + Layer Loops

What You’ll Learn

How to fill a 10×10 matrix with integers 1 through 100 in clockwise square-spiral order using four inner passes per layer.

You’ll track shrinking bounds with $low and $high while incrementing a single counter $n.

⭐ Pattern Output

Spiral from 1 (top-left) to 100 (center). Numbers are spaced for readability (your terminal may use slightly different padding):

Output
  1   2   3   4   5   6   7   8   9  10
 36  37  38  39  40  41  42  43  44  11
 35  64  65  66  67  68  69  70  45  12
 34  63  84  85  86  87  88  71  46  13
 33  62  83  96  97  98  89  72  47  14
 32  61  82  95 100  99  90  73  48  15
 31  60  81  94  93  92  91  74  49  16
 30  59  80  79  78  77  76  75  50  17
 29  58  57  56  55  54  53  52  51  18
 28  27  26  25  24  23  22  21  20  19
1

Complete PHP Program

Five layers shrink the rectangle from 0..9 inward; each side walk advances $n.

PHP
<?php
$a = [];
$low = 0;
$high = 9;
$n = 1;
$layers = 5;

for ($i = 0; $i < $layers; $i++, $low++, $high--) {
    for ($j = $low; $j <= $high; $j++, $n++) {
        $a[$i][$j] = $n;
    }
    for ($j = $low + 1; $j <= $high; $j++, $n++) {
        $a[$j][$high] = $n;
    }
    for ($j = $high - 1; $j >= $low; $j--, $n++) {
        $a[$high][$j] = $n;
    }
    for ($j = $high - 1; $j > $low; $j--, $n++) {
        $a[$j][$low] = $n;
    }
}

$size = 10;
$w = strlen((string) ($size * $size));
echo "Perfect square spiral" . PHP_EOL;
for ($i = 0; $i < $size; $i++) {
    for ($j = 0; $j < $size; $j++) {
        echo str_pad((string) $a[$i][$j], $w, ' ', STR_PAD_LEFT) . ' ';
    }
    echo PHP_EOL;
}

🧠 How It Works

1

Bounds and counter

$low and $high delimit the current ring; $n is the next value to place.

State
2

Top edge

First inner loop writes row $i from column $low to $high.

Left to right
3

Right and bottom

Second loop walks down column $high (excluding the corner already filled). Third loop walks row $high right to left.

Down then left
4

Left edge up

Fourth loop moves up column $low from $high - 1 while $j > $low, skipping corners.

Bottom to top
=

Print pass

After filling $a, nested loops print every cell with padding. Total placement work is O(n²) for size n.

2

Variation — User Input (CLI) Version

Reads an even size between 4 and 20 (same ring logic; odd sizes are rejected for this exact four-loop layout). Default 10 if input is empty.

PHP
<?php
echo "Enter matrix size (even 4-20, blank = 10): ";
$line = trim(fgets(STDIN));
$size = $line === '' ? 10 : (int) $line;

if ($size < 4 || $size > 20 || $size % 2 !== 0) {
    echo "Use an even size between 4 and 20. Using 10." . PHP_EOL;
    $size = 10;
}

$a = [];
$low = 0;
$high = $size - 1;
$n = 1;
$layers = intdiv($size, 2);

for ($i = 0; $i < $layers; $i++, $low++, $high--) {
    for ($j = $low; $j <= $high; $j++, $n++) {
        $a[$i][$j] = $n;
    }
    for ($j = $low + 1; $j <= $high; $j++, $n++) {
        $a[$j][$high] = $n;
    }
    for ($j = $high - 1; $j >= $low; $j--, $n++) {
        $a[$high][$j] = $n;
    }
    for ($j = $high - 1; $j > $low; $j--, $n++) {
        $a[$j][$low] = $n;
    }
}

$w = strlen((string) ($size * $size));
echo "Perfect square spiral" . PHP_EOL;
for ($i = 0; $i < $size; $i++) {
    for ($j = 0; $j < $size; $j++) {
        echo str_pad((string) $a[$i][$j], $w, ' ', STR_PAD_LEFT) . ' ';
    }
    echo PHP_EOL;
}

💡 Tips for Enhancement

Try These

  • Draw direction arrows in comments for each of the four inner loops
  • Export the matrix as CSV for spreadsheet visualization
  • Try counterclockwise by reversing loop directions
  • Replace numbers with colors or Unicode blocks by value ranges
  • Refactor the four walks into a small function per side

Avoid

  • Off-by-one on the last left column loop (j > $low skips the corner)
  • Changing loop order without retesting corner cells
  • Assuming odd sizes work without adjusting layer termination
  • Printing HTML <div> per cell in CLI examples

Key Takeaways

1

Spiral fill is four directed passes per ring, with bounds moving inward.

2

One counter $n can drive the entire sequence if updates are ordered correctly.

3

Storing in a 2D array separates construction from pretty-printing.

4

Padding keeps wide values like 100 aligned in monospace output.

❓ Frequently Asked Questions

Each loop traces one side of the current rectangle: top, right, bottom, and left, avoiding double-writing corners by careful start and end indices.
This exact four-loop layout is demonstrated for even sizes (center is a block). Odd sizes usually need an extra center step or different bounds; the CLI variation rejects odd input for safety.
On CodeToFun you can continue with PHP star pattern programs for a different style of pattern practice.
O(n²) time and space for an n×n matrix.

Explore More PHP Patterns!

Move from numeric spirals to star grids and mixed character patterns.

Star Patterns →
Did you know?

LeetCode-style “spiral matrix” problems use the same ring idea; pre-allocating a 2D array then filling by perimeter is a common interview pattern.

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