Number Pattern 38 in PHP

What You’ll Learn
How to print Number Pattern 38 in PHP using nested loops. The first row prints $rows numbers, and each next row prints one fewer number than the previous.
You’ll use a counter variable to keep printing numbers sequentially across rows.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15Complete PHP Program
The inner loop counts down from $rows to the current row index $i, so each next row prints one fewer number.
<?php
$rows = 5;
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
for ($j = $rows; $j >= $i; $j--) {
echo $k++ . " ";
}
echo PHP_EOL;
}🧠 How It Works
Initialize rows and counter
$rows = 5; sets the triangle size and $k = 1; starts the sequential numbering.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) moves from row 1 to row $rows.
Inner loop (shrinking width)
for ($j = $rows; $j >= $i; $j--) prints $rows - $i + 1 numbers on row $i.
Print and increment
echo $k++; prints the current counter value and increments it for the next position.
Shrinking number triangle
Total prints are n(n+1)/2, so runtime 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);
}
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
for ($j = $rows; $j >= $i; $j--) {
echo $k++ . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Use
str_pad()to align multi-digit columns (10, 11, 12, ...) - Start from a different initial value by setting
$kaccordingly - Print commas instead of spaces for CSV-style output
- Reverse the structure (growing triangle) by changing the inner-loop bounds
- Store each row in an array for later processing
Avoid
- Forgetting to print a newline after each row
- Using
$rowsless than 1 without validation - Mixing row and column responsibilities (outer loop = rows)
- Assuming spacing stays aligned when values become multi-digit
Key Takeaways
A counter prints sequential values across all rows.
Each next row prints one fewer number than the previous.
Total prints are n(n+1)/2 for n rows.
Runtime grows as O(n²).
❓ Frequently Asked Questions
$i = $rows, the inner loop runs only once (from $rows down to $rows).trim() it before echoing, or print spaces only between values.$i so each row prints one more value than the previous.Explore More PHP Number Patterns!
Practice counters and loop bounds by trying more shrinking and growing patterns.
The total count of printed numbers forms a triangular number. For $rows = 5, that’s 15 numbers (1 through 15).
12 people found this page helpful
