PHP Hollow Square Pattern (Border of 1s)

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

What Is This Pattern?

A hollow square border prints 1 only on the edges of an n × n grid and leaves the interior as spaces.

Remember
Rule: print 1 on the border; spaces inside

1 1 1 1 1
1       1
1       1
1       1
1 1 1 1 1   ← size = 5

In PHP loop $i and $j from 1 to $size. Print "1 " when the cell is on the border; otherwise print " ".

How to Solve It

One nested loop over every cell, plus a four-way border check.

MethodIdeaBest for
Border conditionIf $i/$j on edge → 1, else spacesLearning, interviews, exams
Size inputSame logic with a user-chosen $sizePractice / demos

Pseudocode

Pseudocode
for i from 1 to size:
    for j from 1 to size:
        if i is 1 or size, or j is 1 or size:
            print "1 "
        else:
            print "  "
    print newline

Cheat sheet

GoalPattern
Walk rowsfor ($i = 1; $i <= $size; $i++)
Walk columnsfor ($j = 1; $j <= $size; $j++)
Border testif ($i == 1 || $i == $size || $j == 1 || $j == $size)
Print border / interiorecho "1 "; / echo " ";
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo "1 " / echo " "Stays on the same lineEach cell
echo PHP_EOLEnds the current lineAfter the inner loop finishes a row

Print cells without a newline, then end the row once.

Live Preview

Change the square size and the hollow border updates instantly.

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

Live result 5 × 5 · 16 border cells
1 1 1 1 1 
1       1 
1       1 
1       1 
1 1 1 1 1 

Worked Walkthrough — $size = 4

Trace each row: top and bottom are solid; middle rows keep only the ends.

$iBorder rulePrinted row
1Top row — all 11 1 1 1
2$j == 1 or $j == 41 1
3$j == 1 or $j == 41 1
4Bottom row — all 11 1 1 1

Border cells for size n = 4(n - 1) when n >= 2 (corners counted once).

PHP Programs

Three complete programs: fixed 5×5, CLI input size, and an asterisk-border variant. Use View Output for sample results.

Example 1 — Fixed $size = 5

Nested loops with a border condition — ideal for first demos.

PHP
<?php
$size = 5;

for ($i = 1; $i <= $size; $i++) {
    for ($j = 1; $j <= $size; $j++) {
        if ($i == 1 || $i == $size || $j == 1 || $j == $size)
            echo "1 ";
        else
            echo "  ";
    }

    echo PHP_EOL;
}

How It Works

1. Grid walk. Outer $i picks the row; inner $j picks the column — every cell is visited once.

2. Border test. If $i or $j is on the edge, print "1 "; otherwise print " ".

3. New line. echo PHP_EOL after the inner loop starts the next row.

Example 2 — User Input (size)

Read the square size from STDIN and build an n × n hollow frame.

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

if (!is_numeric($input) || (int) $input < 2) {
    echo "Please enter an integer greater than 1." . PHP_EOL;
    exit(1);
}

$size = (int) $input;

for ($i = 1; $i <= $size; $i++) {
    for ($j = 1; $j <= $size; $j++) {
        if ($i == 1 || $i == $size || $j == 1 || $j == $size)
            echo "1 ";
        else
            echo "  ";
    }

    echo PHP_EOL;
}

How It Works

1. Validate size. Check is_numeric; require $size >= 2 for a hollow frame.

2. Same border logic. Only the bound changes from the literal 5 to the user value.

Example 3 — Asterisk Border ($size = 5)

Same hollow frame — swap 1 for * on the border.

PHP
<?php
$size = 5;

for ($i = 1; $i <= $size; $i++) {
    for ($j = 1; $j <= $size; $j++) {
        if ($i == 1 || $i == $size || $j == 1 || $j == $size)
            echo "* ";
        else
            echo "  ";
    }

    echo PHP_EOL;
}

How It Works

1. Same structure. Only the border string changes from "1 " to "* ".

2. Keep spacing. Interior cells still use two spaces so columns stay aligned.

Edge Cases & Pitfalls

Check these before calling the solution done.

AND vs OR

Use && instead of ||

Corners would still print, but side edges would be empty. Border needs || so any edge matches.

one space

Interior prints a single space

Columns drift because border cells use "1 " (two characters). Match width with " ".

size = 1

Single cell

Output is just 1 — no hollow interior. Require $size >= 2 for a frame.

0-based

Loops from 0 but check $size

If indices are 0..$size-1, test $i == 0 || $i == $size - 1 (and the same for $j).

PHP_EOL early

echo PHP_EOL inside the inner loop

That puts every cell on its own line. End the row only after the column loop.

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 / asterisk (Examples 1, 3)O(n²)O(1)
User input (Example 2)O(n²)O(1)

Every cell of the n × n grid is visited once, so work is quadratic in the side length.

Key Takeaways

  • Rule: print 1 when $i or $j is on the edge; otherwise print spaces.
  • Align: use "1 " and " " so every cell is two characters wide.
  • echo vs PHP_EOL: cells stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 43 prints a right-aligned ascending number triangle.

One line: visit every cell; print 1 on the border and spaces inside.

Frequently Asked Questions

It prints characters only on the border (first/last row and first/last column) and leaves the inside blank with spaces.
It checks if $i is 1 or $size, or if $j is 1 or $size. If any is true, print 1; otherwise print spaces.
Use a $size variable and loop from 1 to $size for both $i and $j. Update the border check to use $size — see Example 2.
Each border cell uses "1 " (digit plus space). Interior cells use " " so columns stay aligned.
Size 2 gives a thin frame. Size 1 prints a single 1 with no hollow interior.
Program 41 prints a centered pyramid of perfect squares. Program 42 prints a hollow square grid using border conditions.
Replace "1 " with "* " or "# " in the if branch — see Example 3.
O(n²) for an n×n grid because each cell is visited once.
Use trim(fgets(STDIN)) and check is_numeric($input); validate $size >= 2 for a meaningful hollow frame.

Did you know?

Print 1 when $i == 1, $i == $size, $j == 1, or $j == $size; otherwise print spaces. An n × n grid visits n² cells.

Next: Right-Aligned Number Triangle

Print 1, 1 2, 1 2 3… with leading spaces for right alignment.

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

6 people found this page helpful