Square Number Pattern in PHP

What You’ll Learn
How to print Number Pattern 41 in PHP: consecutive square numbers arranged into rows of odd length (1, 3, 5, 7, 9).
You’ll use a counter $m and print $m * $m in each position before incrementing $m.
⭐ Pattern Output
For 5 rows (odd lengths up to 9), the pattern looks like this:
1
4 9 16
25 36 49 64 81
100 121 144 169 196 225 256
289 324 361 400 441 484 529 576 625Complete PHP Program
The outer loop uses odd counts (1, 3, 5, 7, 9). Each row prints that many square numbers.
<?php
$m = 1;
for ($i = 1; $i <= 9; $i += 2) {
for ($k = 1; $k <= $i; $k++) {
echo ($m * $m) . " ";
$m++;
}
echo PHP_EOL;
}🧠 How It Works
Initialize the counter
$m = 1; is the base number whose square we print.
Outer loop (odd row sizes)
for ($i = 1; $i <= 9; $i += 2) creates row sizes of 1, 3, 5, 7, 9.
Inner loop (print squares)
The inner loop prints exactly $i values using $m * $m, then increments $m.
Odd-length square rows
The total printed count here is 1+3+5+7+9 = 25 values, ending at 25² = 625.
Variation — User Input (CLI) Version
Let the user decide the maximum odd row length at runtime (run from terminal with php):
<?php
echo "Enter the maximum odd row length (e.g., 9): ";
$maxOdd = (int) trim(fgets(STDIN));
if ($maxOdd < 1 || $maxOdd % 2 === 0) {
exit("Please enter a positive odd number." . PHP_EOL);
}
$m = 1;
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($k = 1; $k <= $i; $k++) {
echo ($m * $m) . " ";
$m++;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use
str_pad()to align columns when values become wide - Print cubes using
$m * $m * $m - Center-align the rows by printing leading spaces before each row
- Reset
$meach row to square the same values per row - Store values in an array for later formatting or exporting
Avoid
- Using an even maximum in the odd-length loop (validate input)
- Forgetting to increment
$m - Assuming output alignment without fixed-width formatting
- Mixing HTML spacing with CLI output
Key Takeaways
Values printed are squares: 1, 4, 9, 16, ...
Row lengths grow by 2 (odd counts): 1, 3, 5, 7, 9
A counter $m makes squares progress continuously across rows.
Runtime grows quadratically as the number of printed values increases.
❓ Frequently Asked Questions
25² = 625.$m by 2 (start from 2) so you square even numbers only: 4, 16, 36, ...PHP_EOL with <br> and use CSS (grid/flex) for consistent alignment.Explore More PHP Number Patterns!
Square-number patterns are a fun way to practice arithmetic with nested loops.
The sum of the first n odd numbers is n². That’s why odd-length rows often appear in square-related patterns.
12 people found this page helpful
