PHP Binary Number Triangle Pattern (Starting with 1)

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

What Is This Pattern?

An alternating binary triangle starting with 1 grows one digit per row, printing 0 or 1 from $j % 2 as the inner index counts up — so every row begins with 1.

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

1
10
101
1010
10101   ← rows = 5

In PHP you solve it with ascending outer and inner loops: echo $j % 2 prints each bit, then echo PHP_EOL ends the row. Program 15 is the descending-inner twin (1, 01, 101…).

How to Solve It

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

MethodIdeaBest for
Ascending + $j % 2Count j up; 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 1 to i:
        print j % 2 (no newline)
    print newline

Cheat sheet

GoalPattern
Grow row lengthfor ($i = 1; $i <= $rows; $i++)
Print binary digitfor ($j = 1; $j <= $i; $j++) echo $j % 2;
End the rowecho PHP_EOL;
Flip every bitecho 1 - ($j % 2);
Program 15 twinfor ($j = $i; $j >= 1; $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
10
101
1010
10101

Worked Walkthrough

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

$iInner $j$j % 2Printed row
1111
21, 21, 010
31, 2, 31, 0, 1101
51..51,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 up, print $j % 2.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $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 up from 1 to $i; $j % 2 is the bit — so each row starts with 1.

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 = 1; $j <= $i; $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 = 1; $j <= $i; $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 1010.

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 = $i; $j >= 1; $j--)

That is Program 15 (1, 01, 101). Keep counting up for this pattern.

echo $j

echo $j instead of echo $j % 2

That prints the ascending 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 1 up to $i.
  • Starts with 1: because the first $j is always odd.
  • echo vs PHP_EOL: bits stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 17 prints left-shifted odd numbers in a growing triangle.

One line: for each row length i, print $j % 2 from 1 up to i 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 = 1 then j = 2. That becomes 1 % 2 = 1 then 2 % 2 = 0, so the row is 10.
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 = 1, 2, 3 and j % 2 becomes 1, 0, 1 — concatenated as 101.
Program 16 counts the inner loop up (j = 1 to i) producing 1, 10, 101, 1010, 10101. Program 15 counts down (j = i to 1) producing 1, 01, 101, 0101, 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 up from 1 to $i, so every row starts with 1 — still O(n²) total prints.

Next: Left-Shifted Odd Number Triangle

Continue with rows of odd numbers that slide left as they grow.

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