Alternating 1-0 Triangle in PHP

What You’ll Learn
How to print an alternating 1-0 triangle in PHP using nested loops and the modulo operator %. Each row prints a sequence of 0 and 1 based on whether the loop counter is even or odd.
This is a great mini-exercise for mastering nested loops and understanding how modulo can generate repeating patterns.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
1
01
101
0101
10101Complete PHP Program
We print each digit using $j % 2, which yields 0 for even and 1 for odd values of $j.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j >= 1; $j--) {
echo $j % 2;
}
echo PHP_EOL;
}🧠 How It Works
Set the number of rows
$rows = 5; controls the triangle height.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) increments the row number from 1 up to $rows.
Inner loop (count down)
for ($j = $i; $j >= 1; $j--) prints exactly $i digits on row $i.
Print 0/1 with modulo
echo $j % 2; prints 1 for odd $j and 0 for even $j.
Alternating 1-0 triangle
Because the inner loop counts down, each row begins with the parity of $i (even rows start with 0, odd rows start with 1).
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 = $i; $j >= 1; $j--) {
echo $j % 2;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Flip the direction by looping
$jupward from 1 to$i - Print spaces between digits to make larger triangles readable
- Start with
0every row by using($j + 1) % 2instead - Build a full binary grid by printing fixed-length rows
- Validate input (reject
$rows < 1) in CLI mode
Avoid
- Forgetting the newline after each row
- Assuming user input is always valid (especially empty input)
- Mixing row/column logic (outer loop = rows, inner loop = columns)
- Hardcoding output strings instead of generating via loops
Key Takeaways
Use nested loops to control rows and columns.
$j % 2 generates alternating 0/1 values automatically.
With the countdown inner loop, even rows start with 0 and odd rows start with 1.
The same logic can generate other repeating patterns (like 0123 cycles) using % k.
❓ Frequently Asked Questions
$j % 2 is 1 for odd numbers and 0 for even numbers, so it naturally alternates as $j changes.$j = $i. When $i is even, $i % 2 is 0, so the row starts with 0.1 - ($j % 2) instead of $j % 2. That inverts 0/1 for every position.Explore More PHP Number Patterns!
Once you master modulo-based alternation, try patterns with symmetry, spacing, and right-alignment.
The modulo operator is a common way to create repeating cycles. For example, $x % 3 cycles through 0, 1, 2, which is handy for repeating colors, labels, or pattern symbols.
12 people found this page helpful
