Number Pattern 33 in PHP

What You’ll Learn
How to print Number Pattern 33 in PHP using nested loops. Row $i prints $i numbers, and each number is computed using $i + $j - 1.
This is a neat pattern for practicing how row/column indices translate into printed values.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9Complete PHP Program
The outer loop controls the row. The inner loop prints the value $i + $j - 1 for each column position $j.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo ($i + $j - 1) . " ";
}
echo PHP_EOL;
}🧠 How It Works
Choose the row count
$rows = 5; sets how many lines will be printed.
Outer loop (rows 1..$rows)
for ($i = 1; $i <= $rows; $i++) controls which row is being printed.
Inner loop (columns 1..$i)
for ($j = 1; $j <= $i; $j++) prints $i numbers on the current row.
Compute and print $i + $j - 1
echo ($i + $j - 1) . " "; makes the row start at $i and increase by 1 across columns.
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 ($i + $j - 1) . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$rows < 1) before printing the pattern - Start from 0 by using
($i + $j - 2)instead of($i + $j - 1) - Align rows by printing leading spaces before each row
- Remove the trailing space by building each row as a string and trimming it
- Turn it into a pyramid by printing centered spacing
Avoid
- Forgetting to move to the next line after each row (
PHP_EOL) - Using negative or zero rows without validation
- Mixing row/column responsibilities (outer loop = rows, inner loop = columns)
- Assuming user input is always valid in CLI programs
Key Takeaways
The outer loop prints rows from 1 to $rows.
Row $i prints $i numbers (inner loop runs 1..$i).
Each value is computed using $i + $j - 1, so rows start at their index.
Total printed values are n(n+1)/2, giving O(n²) runtime.
❓ Frequently Asked Questions
$i = 2, the inner loop prints $i + $j - 1. When $j=1, it prints 2; when $j=2, it prints 3.$j = 1, the expression becomes $i + 1 - 1 = $i.($i + $j) will shift everything up by 1, and ($i + $j - 2) will shift everything down by 1.Explore More PHP Number Patterns!
Practice nested loops with progressively richer number patterns and variations.
If you view the values as a grid, each cell increases by 1 as you move right because $j increases by 1 in the formula $i + $j - 1.
12 people found this page helpful
