2. Trace on paper. If the outer loop counts up instead of down, the shortest row prints first.
3. Scale up next. Once the small demo is clear, use Examples 1–2 for five rows or user input.
Edge Cases & Pitfalls
Check these before calling the solution done.
i++
Growing outer loop
Using for ($i = 1; $i <= $rows; $i++) prints the shortest row first. Keep $i = $rows..1.
j++
Ascending inner loop
for ($j = 1; $j <= $i; $j++) prints 12345 style rows — not reverse. Use $j = $i..1.
PHP_EOL inside
Broken rows
If echo PHP_EOL sits inside the inner loop, you get one digit per line. Call it only after the inner loop.
j = rows
Full line every row
Starting $j at $rows every time reprints 54321 on each line. Start at $i.
rows = 1
Single digit
Output is just 1. A good sanity check for input validation.
fgets
Check is_numeric
Bare (int) casts turn non-numeric strings into 0 — prefer is_numeric before casting.
Analysis
Time and Space Complexity
Program
Time
Extra space
Fixed / input (Examples 1–2)
O(n²)
O(1)
Compact rows = 3 (Example 3)
O(n²)
O(1)
Row starting at $i prints i digits. Total = n + (n−1) + … + 1 = n(n+1)/2 → O(n²) time. Only a few loop variables are needed.
Remember
Key Takeaways
Two descending loops: outer $rows..1, inner $i..1.
Longest first: start the outer loop at $rows so the first row is the widest.
Break the row: digits in the inner loop; echo PHP_EOL after it finishes.
Complexity:O(n²) time from n(n+1)/2 digits; O(1) extra space.
One line: for each $i from $rows down to 1, print $i..1, then echo PHP_EOL.
Frequently Asked Questions
A reverse descending triangle: for rows=5 you get 54321 / 4321 / 321 / 21 / 1 — each row prints i down to 1 while the outer loop shrinks.
The inner loop runs $j = $i down to 1, so each row prints $i, $i-1, ..., 1.
Because $rows = 5 and the outer loop starts with $i = $rows. The first row prints from 5 down to 1.
Program 2 prints $i..$rows (left-shifted). Program 3 prints $i..1 (reverse descending) with a shrinking outer loop.
Use echo $j . " " instead of echo $j in the inner loop.
echo $j prints digits on the same line. echo PHP_EOL ends the row after the inner loop finishes.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.
O(n²) for n rows. Total prints are n + (n-1) + … + 1 = n(n+1)/2.
🤔
Did you know?
This pattern prints each row in descending order from $i down to 1. The outer loop shrinks the row length while the inner loop counts downward — producing 54321, 4321, 321, and so on.