Number Pattern 32 in PHP

What You’ll Learn
How to print Number Pattern 32 in PHP using nested loops. Each row prints a growing sequence that starts at 11 and increases based on the row ($i) and column ($j) positions.
You’ll also learn how to generalize the same logic for a user-defined row count in a CLI version.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
11
12 13
13 14 15
14 15 16 17
15 16 17 18 19Complete PHP Program
The outer loop controls rows. The inner loop prints $i numbers in row $i, using the value formula 9 + $i + $j.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo (9 + $i + $j) . " ";
}
echo PHP_EOL;
}🧠 How It Works
Choose the row count
$rows = 5; sets how many lines will be printed.
Outer loop (row control)
for ($i = 1; $i <= $rows; $i++) iterates from row 1 to the last row, so each next row prints one extra number.
Inner loop (columns 1..$i)
for ($j = 1; $j <= $i; $j++) prints exactly $i values for the current row.
Compute and print the number
echo (9 + $i + $j) . " "; generates the sequence starting at 11 and increasing across the row.
Growing number triangle
Total printed values are 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input (CLI) Version
Let the user decide the number of rows at runtime using standard input (run from terminal with php):
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
exit("Rows must be at least 1." . PHP_EOL);
}
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo (9 + $i + $j) . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$rows < 1) before printing the pattern - Change the base value
9to shift the starting number (for example, start at 21) - Align the triangle by adding leading spaces before each row
- Remove the trailing space by building each row as a string and trimming it
- Replace numbers with characters to create alphabet patterns
Avoid
- Forgetting to move to the next line after each row (
PHP_EOL) - Using negative or zero rows without validation
- Mixing row/column logic (keep the outer loop for rows)
- Assuming user input is always valid in CLI programs
Key Takeaways
The outer loop controls rows from 1 to $rows.
The inner loop prints exactly $i numbers on row $i.
The printed value uses the formula 9 + i + j, which makes the first number 11.
Total printed values are n(n+1)/2 for n rows, so runtime is O(n²).
❓ Frequently Asked Questions
9 + $i + $j. For $i=1 and $j=1, it becomes 9+1+1 = 11.$j = 1 to $j = $i, so row $i prints exactly $i numbers.(9 + $i + $j) with (19 + $i + $j) to start at 21.Explore More PHP Number Patterns!
Practice nested loops with progressively richer number patterns and variations.
Since each row prints one more number than the previous, the total count after n rows is a triangular number: 1+2+…+n = n(n+1)/2.
12 people found this page helpful
