Decreasing-Step Number Pattern in PHP

What You’ll Learn
How to print a decreasing-step number pattern in PHP like:
1, 2 6, 3 7 10, 4 8 11 13, 5 9 12 14 15.
The key idea is to print the first value of a row, then repeatedly add a step value that decreases by 1 after each print.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15Complete PHP Program
We set $m to $rows - 1 for each row, then update $k by adding the decreasing step.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
echo $i . " ";
$m = $rows - 1;
$k = $i + $m;
for ($j = 1; $j < $i; $j++) {
echo $k . " ";
$m--;
$k = $k + $m;
}
echo PHP_EOL;
}🧠 How It Works
Choose the row count
$rows = 5; controls the triangle height.
Print the first number
echo $i; prints the first value of the row (1, 2, 3, 4, 5).
Initialize the decreasing step
$m = $rows - 1; starts at 4, then becomes 3, 2, 1 as we print values.
Update k by adding the step
We compute $k and then repeatedly do $k = $k + $m while $m decreases.
Decreasing-step rows
The decreasing step size is what creates the distinctive diagonal structure of this pattern.
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) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $rows; $i++) {
echo $i . " ";
$m = $rows - 1;
$k = $i + $m;
for ($j = 1; $j < $i; $j++) {
echo $k . " ";
$m--;
$k = $k + $m;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Increase
$rowsto generate a larger triangle - Align multi-digit output with
printf("%3d ", $value) - Store each row in an array and join it to avoid trailing spaces
- Experiment with different starting steps (not just
$rows - 1) - Convert it into a matrix by printing a fixed column count
Avoid
- Resetting
$minside the inner loop incorrectly - Forgetting to decrement
$m(the pattern will change) - Skipping input validation in CLI mode
- Assuming output stays single-digit when rows get large
Key Takeaways
The first value of each row is the row number $i.
A step value starts at $rows - 1 and decreases after each print.
Updating $k with the decreasing step builds the row sequence.
The total printed values for r rows is r(r+1)/2.
❓ Frequently Asked Questions
$rows - 1 creates the correct spacing between values so the pattern lines up into diagonals as rows increase.$rows = 10. The same logic works because $m is set to $rows - 1 per row.implode(" ", $row) at the end of each row.Explore More PHP Number Patterns!
Patterns with changing step sizes are great practice for sequence logic and loop thinking.
Many seemingly complex patterns can be generated by tracking a small amount of state (like a step size) and updating it each iteration.
12 people found this page helpful
