Hollow Square of 1s in PHP

What You’ll Learn
How to print a hollow square border of 1s in PHP using nested loops.
The key idea is to print 1 only on the border cells and print spaces for inner cells.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1Complete PHP Program
If the cell is on the border (first/last row or column), print 1. Otherwise print spaces.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
if ($i === 1 || $i === $n || $j === 1 || $j === $n) {
echo "1 ";
} else {
echo " ";
}
}
echo PHP_EOL;
}🧠 How It Works
Choose the grid size
$n = 5; prints a 5×5 grid.
Loop over rows and columns
Two nested loops visit every cell ($i, $j) in the grid.
Border check
If $i or $j is at the boundary (1 or $n), print 1.
Hollow square
You still check every cell, so runtime is O(n²).
Variation — User Input (CLI) Version
Let the user decide the size $n at runtime using standard input (run from terminal with php):
<?php
echo "Enter n: ";
$n = (int) trim(fgets(STDIN));
if ($n < 2) {
exit("n must be at least 2." . PHP_EOL);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
if ($i === 1 || $i === $n || $j === 1 || $j === $n) {
echo "1 ";
} else {
echo " ";
}
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print a border of another digit (like 9) instead of 1
- Fill the inside with another symbol (like 0) to make a framed square
- Use fixed-width formatting for consistent columns
- Print a hollow rectangle by using different row/column sizes
- Create a double border by checking for
$i===2or$i===$n-1
Avoid
- Printing border and interior using the same branch (you’ll lose the hollow effect)
- Forgetting input validation in the CLI version
- Using
<br>in CLI output (usePHP_EOL) - Assuming spaces render the same in HTML as in console
Key Takeaways
Border cells satisfy $i===1 or $i===$n or $j===1 or $j===$n.
Interior cells print spaces, creating the hollow shape.
Two nested loops visit all cells, giving O(n²).
The same technique works for rectangles and other borders.
❓ Frequently Asked Questions
1. Interior cells print spaces, which makes the square hollow. for visible spaces.n=1, so the CLI variation requires n >= 2.n×n grid.Explore More PHP Number Patterns!
Try more hollow and border-style patterns to sharpen your conditional logic.
Many hollow patterns are built with the same border check: first/last row or first/last column.
12 people found this page helpful
