PHP Binary Number Triangle Pattern (Alternating)

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

What Is This Pattern?

An alternating binary number triangle grows one digit per row, printing 0 or 1 from $j % 2 as the inner index counts down.

Remember
Rule: outer i = 1..rows; inner j = i..1; print j % 2

1
01
101
0101
10101   ← rows = 5

In PHP you solve it with an ascending outer loop and a descending inner loop: echo $j % 2 prints each bit, then echo PHP_EOL ends the row. Program 16 flips the inner direction (1..i) for a related shape.

How to Solve It

Outer loop from 1 to $rows. Inner loop from current $i down to 1, printing $j % 2. End each row with echo PHP_EOL.

MethodIdeaBest for
Descending + $j % 2Count j down; print parity as the bitLearning, interviews, exams
Flip bitsPrint 1 - ($j % 2)Complementary triangle labs

Pseudocode

Pseudocode
for i from 1 to rows:
    for j from i down to 1:
        print j % 2 (no newline)
    print newline

Cheat sheet

GoalPattern
Grow row lengthfor ($i = 1; $i <= $rows; $i++)
Print binary digitfor ($j = $i; $j >= 1; $j--) echo $j % 2;
End the rowecho PHP_EOL;
Flip every bitecho 1 - ($j % 2);
Program 16 twinfor ($j = 1; $j <= $i; $j++) echo $j % 2;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $j % 2Stays on the same lineEach binary digit
echo PHP_EOLEnds the current lineAfter the inner loop

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

Live Preview

Change the row count and the binary triangle updates instantly.

Whole numbers from 1 to 12. Tap a chip or type a value — the preview redraws as you go.

Live result 5 rows · 15 digits
1
01
101
0101
10101

Worked Walkthrough

Trace three outer values when $rows = 5 — watch $j % 2 flip as $j counts down.

$iInner $j$j % 2Printed row
1111
22, 10, 101
33, 2, 11, 0, 1101
55..11,0,1,0,110101

Total digits are 1+2+3+4+5 = 15 — the triangular number n(n+1)/2.

PHP Programs

Three complete programs: fixed height, flipped bits, and CLI input. Use View Output for sample results.

Example 1 — Fixed $rows = 5

Outer grows, inner counts down, print $j % 2.

PHP
<?php
$rows = 5;

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

How It Works

1. Outer grows the length. $i runs from 1 to $rows — that is how many bits each row gets.

2. Inner prints parity. $j counts down from $i to 1; $j % 2 is the bit.

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

Example 2 — Flip with 1 - ($j % 2)

Invert every bit so the first row starts with 0 instead of 1.

PHP
<?php
$rows = 5;

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

How It Works

1. Same loop bounds. Outer and inner ranges match Example 1.

2. Flip the bit. 1 - ($j % 2) turns 1 into 0 and 0 into 1.

3. First row becomes 0. Useful when a lab asks for the complementary binary triangle.

Example 3 — 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 = 1; $i <= $rows; $i++) {
    for ($j = $i; $j >= 1; $j--) {
        echo $j % 2;
    }
    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 stops early. You get four binary rows ending at 0101.

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;

Edge Cases & Pitfalls

Check these before calling the solution done.

wrong twin

for ($j = 1; $j <= $i; $j++)

That is Program 16 (1, 10, 101). Keep counting down for this pattern.

echo $j

echo $j instead of echo $j % 2

That prints the countdown numbers. This pattern needs the parity bit only.

PHP_EOL inside

echo PHP_EOL inside the inner loop

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

rows = 1

Single bit

Output is just 1 — a good sanity check.

rows ≤ 0

Empty output

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

spaces

Do not add spaces between bits

The classic sample is concatenated (10101), not spaced (1 0 1 0 1).

Time and Space Complexity

ProgramTimeExtra space
Fixed / flip / input (Examples 1–3)O(n²)O(1)

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

Key Takeaways

  • Rule: for each row $i, print $j % 2 while $j counts from $i down to 1.
  • Modulo bit: even $j → 0; odd $j → 1.
  • echo vs PHP_EOL: bits stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 16 counts the inner loop up for 1, 10, 101…

One line: for each row length i, print $j % 2 from i down to 1 with echo, then echo PHP_EOL.

Frequently Asked Questions

Modulo 2 returns the remainder after dividing by 2. Any integer is either even (remainder 0) or odd (remainder 1).
On row 2, the inner loop prints j = 2 then j = 1. That becomes 2 % 2 = 0 then 1 % 2 = 1, so the row is 01.
echo $j % 2 stays on the same line. echo PHP_EOL ends the current line. Binary digits use echo; the row break uses echo PHP_EOL after the inner loop.
Row 3 prints j = 3, 2, 1 and j % 2 becomes 1, 0, 1 — concatenated as 101.
Program 15 counts the inner loop down (j = i to 1) producing 1, 01, 101, 0101, 10101. Program 16 counts up (j = 1 to i) producing 1, 10, 101, 1010, 10101.
Yes. Print 1 - (j % 2) instead of j % 2 to flip every digit — first row becomes 0 instead of 1.
O(n²) where n is the number of rows. Total digit prints equal n+(n-1)+…+1 = n(n+1)/2.
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?

Each row prints alternating 0 and 1 using $j % 2. The inner loop counts down from $i to 1, so row length grows each line — still O(n²) total prints.

Next: Column-Wise Alternating Binary

Continue with the ascending-inner twin that starts each row with 1.

Program 16 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