Incrementing Start Number Triangle in PHP

What You’ll Learn
How to print an incrementing start number triangle in PHP using nested for loops. Each row starts from the row number and continues up to $n.
This pattern helps you practice writing an inner loop whose start value depends on the outer loop variable.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
12345
2345
345
45
5Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the last number printed on each row.
Outer loop (row index)
for ($i = 1; $i <= $n; $i++) controls which row you are printing (and what number the row starts with).
Inner loop (print $i..$n)
for ($j = $i; $j <= $n; $j++) prints digits starting from the current row start $i up to $n using echo $j;.
New line
echo PHP_EOL; ends the row and moves to the next line.
Incrementing start triangle
Total numbers printed is still 1+2+…+n = n(n+1)/2, so the time complexity is O(n²) for n rows.
Variation — User Input (CLI) Version
Let the user decide $n at runtime (run from terminal with php):
<?php
echo "Enter the value of n: ";
$n = (int) trim(fgets(STDIN));
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j <= $n; $j++) {
echo $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$n < 1) before printing - Add spaces between numbers (for example,
echo $j . " ";) - Print the descending-start version by counting the outer loop down and printing
1..$i - Right-align the rows by printing leading spaces before each row
- Use the same loop idea to generate alphabet or star patterns
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Mixing row/column logic (outer loop = rows)
- Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop controls the row number (and thus the starting digit).
The inner loop prints from $i to $n on each row.
Total printed digits follow a triangular count: n(n+1)/2.
The same technique works for star patterns and alphabet patterns.
❓ Frequently Asked Questions
$j = $i. As $i increases each row, the first printed digit becomes 1, 2, 3, 4, ...$n to the size you want. For example $n = 7 will print rows starting at 1..7, then 2..7, down to 7.echo $j . " "; instead of echo $j;. You may also want to trim() the row if you build it as a string.Next: PHP Number Pattern 3
Continue to Program 3 to practice another number pattern using nested loops in PHP.
Even though the rows look different, the amount of work is still triangular: you print n + (n-1) + ... + 1 digits, which is n(n+1)/2.
12 people found this page helpful
