PHP Number Triangle Pattern (Alternating Direction)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

An alternating number triangle prints continuous integers across rows: odd rows go left-to-right, even rows go right-to-left. With $rows = 5 you get 1, 3 2, 4 5 6, 10 9 8 7, 11 12 13 14 15.

Remember
Rule: continuous next; odd = ascending, even = end--

1
3 2
4 5 6
10 9 8 7
11 12 13 14 15     ← rows = 5

Unlike Program 50 (fixed digit halves), this shape uses a running counter and flips direction with $i % 2.

How to Solve It

Keep a counter $next. On each row compute $end, then print ascending or descending based on odd/even $i.

MethodIdeaBest for
Counter + direction$next++ always; print $next or $end-- by parityLearning, interviews, demos
Compact traceSame logic with $rows = 3Quick dry-runs on paper

Pseudocode

Pseudocode
next = 1
for i from 1 to rows:
    end = next + i - 1
    for j from 1 to i:
        if i is odd:
            print next
        else:
            print end
            end = end - 1
        next = next + 1
    print newline

Cheat sheet

GoalPattern
Start counter$next = 1;
Row end value$end = $next + $i - 1;
Odd rowecho $next . " ";
Even rowecho $end-- . " ";
Advance always$next++; after each print
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $n . " "Stays on the same lineEach value
echo PHP_EOLEnds the current lineAfter the inner loop

Print values without a newline, then end the row once. Putting echo PHP_EOL inside the inner loop turns the triangle into a vertical list.

Live Preview

Change the row count and the alternating triangle updates instantly.

Use rows from 1 to 9. Tap a chip or type a value — the preview redraws as you go.

Live result 5 rows · 15 values
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15

Worked Walkthrough

Trace the first four rows — watch $next, $end, and direction.

Row $iParity$next start$endPrinted
1odd / asc111
2even / desc233 2
3odd / asc464 5 6
4even / desc71010 9 8 7

Even on even rows, $next still increments once per cell — so numbering stays continuous for the next row.

PHP Programs

Three complete programs: fixed $rows = 5, CLI input, and a compact $rows = 3 demo. Use View Output to reveal sample results.

Example 1 — Fixed $rows = 5

Hard-coded height — odd rows print $next ascending, even rows print $end-- descending.

PHP
<?php
$rows = 5;
$next = 1;

for ($i = 1; $i <= $rows; $i++) {
    $end = $next + $i - 1;

    for ($j = 1; $j <= $i; $j++) {
        if ($i % 2 == 1) {
            echo $next . " ";
        } else {
            echo $end-- . " ";
        }
        $next++;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Compute the row’s last value. $end = $next + $i - 1 is the reverse start for even rows.

2. Branch on parity. Odd rows print $next; even rows print $end--.

3. Always advance $next. Increment after every cell so the next row continues the sequence, then end the line with echo PHP_EOL.

Example 2 — User Input Rows

Read the row count at runtime — counter and direction logic stay the same.

PHP
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));

if (!is_numeric($input) || (int) $input <= 0) {
    echo "Please enter a positive integer." . PHP_EOL;
    exit(1);
}

$rows = (int) $input;
$next = 1;

for ($i = 1; $i <= $rows; $i++) {
    $end = $next + $i - 1;

    for ($j = 1; $j <= $i; $j++) {
        if ($i % 2 == 1) {
            echo $next . " ";
        } else {
            echo $end-- . " ";
        }
        $next++;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Same counter core. Only the source of $rows changes from a literal to CLI input.

2. Entering 4 stops early. You get four rows ending at 10 9 8 7.

3. Safer input tip. Cap demos for readable output:

Safer input tip
if (!is_numeric($input) || (int) $input < 1 || (int) $input > 9) {
    echo "Enter a whole number from 1 to 9." . PHP_EOL;
    exit(1);
}

Example 3 — Compact $rows = 3

Smaller height for quick tracing of $next, $end, and odd/even branches.

PHP
<?php
$rows = 3;
$next = 1;

for ($i = 1; $i <= $rows; $i++) {
    $end = $next + $i - 1;

    for ($j = 1; $j <= $i; $j++) {
        if ($i % 2 == 1) {
            echo $next . " ";
        } else {
            echo $end-- . " ";
        }
        $next++;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Only three rows. Easy to dry-run every increment and both parity branches on paper.

2. Same formula. Nothing changes except $rows — proving the pattern scales.

3. One even row in the middle. Row 2 is the only reverse print — the zig-zag is obvious.

Edge Cases & Pitfalls

Check these before calling the solution done.

Forget end

Compute $end before the inner loop

Even rows need $end = $next + $i - 1 as the reverse start. Skipping it breaks the zig-zag.

next++

Always increment $next

Even when printing $end--, still call $next++ so the next row continues correctly.

Newline

Do not put PHP_EOL inside the inner loop

Call echo PHP_EOL only after all values on the row are printed.

Reset next

Do not reset the counter per row

Putting $next = 1 inside the outer loop restarts every row and breaks continuity.

rows = 1

Single value

Output is just 1. A good sanity check for input validation.

fgets

Check is_numeric

Bare (int) casts turn non-numeric strings into 0 — prefer is_numeric before casting.

Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)

Total prints are 1 + 2 + … + n = n(n + 1) / 2 — quadratic in n. Only a few integers of extra memory.

Key Takeaways

  • Rule: continuous $next; odd rows ascending, even rows $end--.
  • Set $end: $end = $next + $i - 1 before printing an even row.
  • Break the row: call echo PHP_EOL only after the inner loop.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each row, print $i continuous numbers — left-to-right if odd, right-to-left if even — then end the line.

Frequently Asked Questions

Row 2 is even, so it prints in reverse. The row contains numbers 2 and 3, but they are printed as 3 2 using $end--.
Even rows print right-to-left for the zig-zag effect. We compute $end = $next + $i - 1 and decrement while printing.
A running counter $next increments once per printed value and is never reset between rows.
Program 50 concatenates fixed digit sequences per row. Program 51 uses a continuous counter and alternates print direction on odd/even rows.
Printing a number (and space) stays on the same line. Printing PHP_EOL ends the current row. Values use echo without a newline; the row break uses echo PHP_EOL after the inner loop.
O(n²) for n rows because total printed numbers are 1+2+…+n = n(n+1)/2.
Before printing row $i, the last number is $next + $i - 1 — the reverse start when the row is even.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.

Did you know?

Numbers stay continuous via a running counter $next. Odd rows print ascending; even rows print descending using $end = $next + $i - 1. Total prints = n(n+1)/2 — time O(n²).

Next: Increasing-Decreasing Palindrome Pattern

Continue with the next pattern in the PHP number-pattern series.

Program 52 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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