Alternating 1-0 Pattern in PHP

What You’ll Learn
How to print an alternating 1-0 pattern in PHP that grows row by row: 1, 10, 101, 1010, 10101.
We’ll use nested loops and % 2 to generate repeating 1 and 0 digits automatically.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
10
101
1010
10101Complete PHP Program
The inner loop counts up from 1, so each row starts with 1 and then alternates using $j % 2.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j % 2;
}
echo PHP_EOL;
}🧠 How It Works
Set the number of rows
$rows = 5; controls the height of the triangle.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) picks the current row length $i.
Inner loop (columns)
for ($j = 1; $j <= $i; $j++) runs from 1 to $i, printing one digit per iteration.
Alternate with modulo
echo $j % 2; prints 1 when $j is odd and 0 when it’s even.
Rows always start with 1
Because the first column is always j = 1, every row begins with 1, then alternates as j increases.
Variation — User Input (CLI) Version
Let the user decide the number of rows at runtime using standard input (run from terminal with php):
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j % 2;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Start each row with
0by printing($j + 1) % 2 - Invert digits with
1 - ($j % 2) - Print spaces between digits for readability on big rows
- Build a fixed-width binary rectangle by keeping columns constant
- Validate CLI input to prevent 0 or negative rows
Avoid
- Forgetting the newline after each row
- Hardcoding outputs (generate with loops instead)
- Mixing row/column logic (outer loop = rows, inner loop = columns)
- Ignoring invalid CLI input (empty input becomes 0)
Key Takeaways
The outer loop controls the row length from 1 to $rows.
The inner loop prints $j % 2 to generate alternating digits.
Because $j starts at 1, every row begins with 1.
You can create other cycles with % k (like repeating 012 using % 3).
❓ Frequently Asked Questions
$j = 1, and 1 % 2 is 1.echo ($j + 1) % 2; inside the loop to shift the alternation.1 - ($j % 2) to flip 0 and 1.Explore More PHP Number Patterns!
Try combining modulo with alignment to build checkerboards, grids, and zig-zag patterns.
You can generate many repeating patterns by changing the modulus. For example, $j % 4 cycles through 1, 2, 3, 0 as $j increases.
12 people found this page helpful
