Alternating Row Direction Pattern in PHP

What You’ll Learn
How to print an alternating row direction number pattern in PHP using nested loops and an odd/even row check.
Odd rows print left-to-right increasing values, while even rows print right-to-left decreasing values.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15Complete PHP Program
A running counter generates values, and row parity decides whether to print forward or reverse.
<?php
$k = 1;
$m = 1;
for ($i = 1; $i <= 5; $i++) {
$m = $k + $i - 1;
for ($j = 1; $j <= $i; $j++) {
if ($i % 2 == 1) {
echo $k . " ";
} else {
echo $m-- . " ";
}
$k++;
}
echo PHP_EOL;
}🧠 How It Works
Initialize counters
$k tracks next number; $m is used for reverse printing in even rows.
Prepare reverse start
$m = $k + $i - 1; sets the highest value for current row when reversing.
Parity check
If row is odd, print $k. If even, print $m--. Then increment $k either way.
Next row
echo PHP_EOL; ends row output and moves to next line.
Zigzag row order
Total printed numbers are 1+2+...+n, giving O(n²) complexity.
Variation — User Input (CLI) Version
This version takes row count from user input (run from terminal with php):
<?php
echo "Enter number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
$m = $k + $i - 1;
for ($j = 1; $j <= $i; $j++) {
if ($i % 2 == 1) {
echo $k . " ";
} else {
echo $m-- . " ";
}
$k++;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spacing alignment with
str_pad()for neat columns - Start from any custom seed value instead of 1
- Invert the parity rule (odd rows reverse, even rows forward)
- Generate the same pattern in a 2D array first
- Build a web form to let users choose row count
Avoid
- Forgetting to update
$mat each new row - Incrementing
$kin only one parity branch - Skipping input validation for row count
- Using HTML wrappers in algorithm-focused CLI output
Key Takeaways
A running counter gives consecutive values across all rows.
Row parity determines print direction (forward vs reverse).
$m = $k + $i - 1 helps print even rows in reverse order.
The nested-loop structure can create many zigzag number patterns.
❓ Frequently Asked Questions
$m downwards while $k still advances in the background.echo strings, but readability may decrease for larger numbers.Explore More PHP Number Patterns!
Practice row-direction logic with more loop-driven number challenges.
Alternating row-direction patterns are often used to teach state management, because output order changes while the underlying sequence remains continuous.
12 people found this page helpful
