Alternating Row Direction Pattern in PHP

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Nested Loops + Condition

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:

Output
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
1

Complete PHP Program

A running counter generates values, and row parity decides whether to print forward or reverse.

PHP
<?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

1

Initialize counters

$k tracks next number; $m is used for reverse printing in even rows.

Setup
2

Prepare reverse start

$m = $k + $i - 1; sets the highest value for current row when reversing.

Row prep
3

Parity check

If row is odd, print $k. If even, print $m--. Then increment $k either way.

Direction logic
4

Next row

echo PHP_EOL; ends row output and moves to next line.

Line break
=

Zigzag row order

Total printed numbers are 1+2+...+n, giving O(n²) complexity.

2

Variation — User Input (CLI) Version

This version takes row count from user input (run from terminal with php):

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 $m at each new row
  • Incrementing $k in only one parity branch
  • Skipping input validation for row count
  • Using HTML wrappers in algorithm-focused CLI output

Key Takeaways

1

A running counter gives consecutive values across all rows.

2

Row parity determines print direction (forward vs reverse).

3

$m = $k + $i - 1 helps print even rows in reverse order.

4

The nested-loop structure can create many zigzag number patterns.

❓ Frequently Asked Questions

Row 4 is even, so it prints from computed $m downwards while $k still advances in the background.
Yes. Increase row limit or take rows from input as shown in the variation.
Remove trailing spaces in echo strings, but readability may decrease for larger numbers.
O(n²) due to triangular count of printed values.

Explore More PHP Number Patterns!

Practice row-direction logic with more loop-driven number challenges.

All Number Patterns →
Did you know?

Alternating row-direction patterns are often used to teach state management, because output order changes while the underlying sequence remains continuous.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful