PHP Alternating Number Triangle Pattern (Zigzag)

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

What Is This Pattern?

An alternating zigzag number triangle shrinks from rows to 1. Odd lengths print 1..i; even lengths print i..1.

Remember
Rule: for i = n..1, if i odd print 1..i else print i..1

12345
4321
123
21
1   ← 5 rows

In PHP you solve it with a descending outer loop plus if/else on $i % 2: digits use echo $j, then echo PHP_EOL ends the row. Program 12 repeats one digit per row; this pattern prints a sequence and flips direction.

How to Solve It

Outer loop counts down from $rows to 1. If $i is odd, print 1..$i; if even, print $i..1. End each row with echo PHP_EOL.

MethodIdeaBest for
if / else loopsParity picks ascending or descending inner loopLearning, interviews, exams
start / end / stepOne inner loop driven by three boundsLeaner demos once parity clicks

Pseudocode

Pseudocode
for i from rows down to 1:
    if i is even:
        for j from i down to 1: print j
    else:
        for j from 1 to i: print j
    print newline

Cheat sheet

GoalPattern
Shrink row lengthfor ($i = $rows; $i >= 1; $i--)
Odd length (ascend)for ($j = 1; $j <= $i; $j++) echo $j;
Even length (descend)for ($j = $i; $j >= 1; $j--) echo $j;
Pick directionif ($i % 2 === 0) { ... } else { ... }
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $jStays on the same lineEach digit in the sequence
echo PHP_EOLEnds the current lineAfter the inner loop

Print all digits without a newline, then end the row once.

Live Preview

Change the row count and the zigzag triangle updates instantly — capped at 9 so every digit stays a single character.

Whole numbers from 1 to 9 (single digits). Tap a chip or type a value — the preview redraws as you go.

Live result 5 rows · 15 digits
12345
4321
123
21
1

Worked Walkthrough

Trace $rows = 5 — each row length $i, its parity, the inner range, and the printed row.

$iParityInner $jPrinted row
5odd1..512345
4even4..14321
3odd1..3123
2even2..121
1odd1..11

Row length is always $i; only the travel direction of $j changes with parity. Total digits: n(n+1)/2.

PHP Programs

Three complete programs: fixed height, CLI input, and a start/end/step one-loop form. Use View Output for sample results.

Example 1 — Fixed $rows = 5

Outer loop shrinks the length; if/else picks ascending or descending digits.

PHP
<?php
$rows = 5;

for ($i = $rows; $i >= 1; $i--) {
    if ($i % 2 === 0) {
        for ($j = $i; $j >= 1; $j--) {
            echo $j;
        }
    } else {
        for ($j = 1; $j <= $i; $j++) {
            echo $j;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Outer shrinks the length. $i starts at $rows and moves toward 1 — that is how many digits each row gets.

2. Parity picks the direction. Even $i prints $i..1; odd $i prints 1..$i.

3. End the row. Call echo PHP_EOL; only after the chosen inner loop finishes.

Example 2 — User Input

Read the row count from the CLI. Prefer is_numeric in real apps (shown in the tip below).

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

for ($i = $rows; $i >= 1; $i--) {
    if ($i % 2 === 0) {
        for ($j = $i; $j >= 1; $j--) {
            echo $j;
        }
    } else {
        for ($j = 1; $j <= $i; $j++) {
            echo $j;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

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

2. Entering 4 starts even. The first row is length 4, so it opens with 4321.

3. Safer input tip. Bare (int) casts turn letters into 0. Prefer:

Safer input
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 1) {
    echo "Enter a positive whole number." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

Example 3 — start / end / step

One inner loop — compute direction up front from parity.

PHP
<?php
$rows = 5;

for ($i = $rows; $i >= 1; $i--) {
    $start = ($i % 2 === 0) ? $i : 1;
    $end   = ($i % 2 === 0) ? 1 : $i;
    $step  = ($i % 2 === 0) ? -1 : 1;

    for ($j = $start; $step > 0 ? $j <= $end : $j >= $end; $j += $step) {
        echo $j;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Same zigzag rule. Odd lengths still climb; even lengths still fall.

2. Bounds replace the branch. $start, $end, and $step encode the two if/else loops in one place.

3. Learn the branch first. Prefer Examples 1–2 in class; use this form once the parity rule is clear.

Edge Cases & Pitfalls

Check these before calling the solution done.

echo $i

echo $i instead of echo $j

That repeats the row length. This pattern prints the sequence value of $j.

swapped parity

Odd descends / even ascends

Swapping the branches flips the zigzag and no longer matches 12345 / 4321.

PHP_EOL inside

echo PHP_EOL inside the inner loop

That puts each digit on its own line. Print digits without a newline; call echo PHP_EOL only after the row finishes.

rows = 1

Single digit

Output is just 1 — a good sanity check.

rows ≤ 0

Empty output

The outer loop never runs. Validate and prompt again for clearer UX.

multi-digit

$rows > 9

echo 10 prints two characters. Labs usually stick to 1–9 for a clean single-digit look.

Time and Space Complexity

ProgramTimeExtra space
if / else loops (Examples 1–2)O(n²)O(1)
start / end / step (Example 3)O(n²)O(1)

There are n rows printing n+(n-1)+…+1 digits, so total work is n(n+1)/2.

Key Takeaways

  • Rule: for $i = n..1, odd lengths print 1..i; even lengths print i..1.
  • Print $j: the sequence value lives in the inner counter, not the row length.
  • echo vs PHP_EOL: digits stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 14 keeps only odd-length rows of ascending sequences.

One line: shrink $i from n to 1; use $i % 2 to print 1..i or i..1 with echo $j, then echo PHP_EOL.

Frequently Asked Questions

The program checks whether i is even or odd. For odd i it prints 1..i ascending; for even i it prints i..1 descending, creating a zigzag direction.
The second row from the top has length i = 4, which is even. The even branch runs for ($j = i; $j >= 1; $j--) and prints 4, 3, 2, 1.
echo stays on the same line. echo PHP_EOL ends the current line. Digits use echo $j; the row break uses echo PHP_EOL after the inner loop.
Program 12 repeats the row digit with for ($j = $i; $j <= $rows; $j++) (11111, 2222, 333, 44, 5). Program 13 prints sequential digits 1..i or i..1 and alternates direction using i % 2.
O(n²) where n is the number of rows. Total echo calls equal n+(n-1)+…+1 = n(n+1)/2.
Yes. Swap the if and else branches so odd rows descend and even rows ascend — the zigzag still works, just mirrored.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int so bad input does not produce unexpected results.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you know?

Odd row length i prints 1..i; even row length prints i..1. The outer loop shrinks from rows to 1, and i % 2 flips direction — still O(n²) total digit prints.

Next: Odd-Length Descending Triangle

Continue with rows that keep only odd lengths of ascending digits.

Program 14 tutorial →

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