Number Pattern 34 in PHP

What You’ll Learn
How to print Number Pattern 34 in PHP using nested loops. The loops start from 0, and each value is computed as $i + $j.
This is a great exercise to see how changing loop start values (0-based indexing) affects the printed output.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
0
1 2
2 3 4
3 4 5 6
4 5 6 7 8
5 6 7 8 9 10Complete PHP Program
The outer loop runs from 0 to $rows. For each row $i, the inner loop prints values from $i + 0 up to $i + $i.
<?php
$rows = 5;
for ($i = 0; $i <= $rows; $i++) {
for ($j = 0; $j <= $i; $j++) {
echo ($i + $j) . " ";
}
echo PHP_EOL;
}🧠 How It Works
Choose the maximum row index
$rows = 5; prints rows from 0 through 5 (total 6 rows).
Outer loop (rows 0..$rows)
for ($i = 0; $i <= $rows; $i++) controls which row is being printed.
Inner loop (columns 0..$i)
for ($j = 0; $j <= $i; $j++) prints $i+1 values on row $i.
Compute and print $i + $j
echo ($i + $j) . " "; starts each row at $i and increments by 1 across the row.
0-based growing 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 maximum row index at runtime using standard input (run from terminal with php):
<?php
echo "Enter the maximum row index: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 0) {
exit("Row index must be 0 or greater." . PHP_EOL);
}
for ($i = 0; $i <= $rows; $i++) {
for ($j = 0; $j <= $i; $j++) {
echo ($i + $j) . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Keep 0-based loops to practice indexing, or switch to 1-based loops for more common patterns
- Remove the trailing space by building each row as a string and trimming it
- Right-align the triangle by printing leading spaces before each row
- Change the formula to create different diagonals (for example,
$i + 2*$j) - Print the same pattern using arrays instead of echoing directly
Avoid
- Using negative row indices without validation
- Forgetting the newline after each row (
PHP_EOL) - Mixing row/column responsibilities (outer loop = rows, inner loop = columns)
- Assuming CLI input is always valid
Key Takeaways
The outer loop counts from 0 to $rows, producing $rows+1 rows.
The inner loop prints $i+1 values on row $i (columns 0..$i).
Each value is computed using $i + $j, so the row starts at $i and increases.
Total printed values are n(n+1)/2, giving O(n²) runtime.
❓ Frequently Asked Questions
$i=1, the inner loop prints $i+$j for $j=0 and $j=1, which gives 1 and 2.$rows = 4 because the loop includes row 0.$i and $j from 1 and print $i + $j - 1. That produces 1, then 2 3, then 3 4 5, and so on.Explore More PHP Number Patterns!
Practice nested loops with progressively richer number patterns and variations.
With 0-based indices, each row starts at the same value as the row index because the first column has $j=0, making the first value $i + 0.
12 people found this page helpful
