Alternating 1s and 0s Pattern in PHP

What You’ll Learn
How to print Number Pattern 40 in PHP: a decreasing-width triangle where each row prints either all 1s or all 0s.
Odd-numbered rows print 1 and even-numbered rows print 0, controlled by the modulus check $i % 2.
⭐ Pattern Output
For $rows = 5, the pattern looks like this:
11111
0000
111
00
1Complete PHP Program
The inner loop prints $rows - $i + 1 characters. The printed digit depends on whether $i is odd or even.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j <= $rows; $j++) {
echo ($i % 2 === 0) ? "0" : "1";
}
echo PHP_EOL;
}🧠 How It Works
Set the row count
$rows = 5; controls both the height and the first row width.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) moves from row 1 to row $rows.
Inner loop (decreasing width)
for ($j = $i; $j <= $rows; $j++) prints fewer characters each row.
Choose 1 or 0 using parity
($i % 2 === 0) decides the digit for the entire row.
Alternating rows
Total printed characters are n(n+1)/2, so runtime is O(n²).
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) {
exit("Rows must be at least 1." . PHP_EOL);
}
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j <= $rows; $j++) {
echo ($i % 2 === 0) ? "0" : "1";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Start with 0 on the first row by swapping the parity output
- Print spaces between digits for readability
- Replace 1/0 with any two characters (like
*and-) - Center-align the triangle by printing leading spaces
- Make it a growing triangle by changing the inner loop bounds
Avoid
- Forgetting the newline after each row
- Using invalid row counts without validation
- Printing different digits within a single row (this pattern is row-based)
- Assuming browser output matches CLI output without changing line breaks
Key Takeaways
Odd rows print 1; even rows print 0.
Each row gets shorter because the inner loop starts at $i.
Total printed characters are n(n+1)/2.
Runtime is O(n²) for n rows.
❓ Frequently Asked Questions
0. It prints 4 characters because the inner loop runs from $j=2 to $j=5.$j (column) instead of $i (row).PHP_EOL with <br> so the output breaks lines in HTML.Explore More PHP Number Patterns!
Try more bit-style patterns to strengthen your loop fundamentals.
The parity check $i % 2 is a common trick for alternating outputs (like 0/1, true/false, or even zebra-striping UI rows).
12 people found this page helpful
