Ascending Number Triangle in PHP

What You’ll Learn
How to print an ascending number triangle in PHP using nested for loops. Each row starts at 1 and prints up to the current row index: 1, 12, 123, and so on.
This is one of the best beginner exercises for understanding how the outer loop controls rows and the inner loop controls how many numbers appear per row.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1
12
123
1234
12345Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets how many rows will be printed.
Outer loop (row growth)
for ($i = 1; $i <= $n; $i++) controls the row number. Each next row prints one more digit than the previous.
Inner loop (print 1..$i)
for ($j = 1; $j <= $i; $j++) prints digits from 1 up to the current row limit $i.
New line
echo PHP_EOL; ends the row and moves to the next line.
Ascending number triangle
Total digits printed: 1+2+…+n = n(n+1)/2, so the time complexity is O(n²).
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 = 1; $j <= $i; $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 version by counting the outer loop down (Program 1)
- Right-align the triangle by printing leading spaces
- Turn it into Floyd’s triangle by printing a running counter instead of
$j
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 grows from 1 to $n.
The inner loop prints digits from 1 to $i on each row.
Total printed digits follow a triangular count: n(n+1)/2.
This pattern is a foundation for many other patterns and loop exercises.
❓ Frequently Asked Questions
$j = 1. Only the stop value changes (it stops at $i), so each row starts at 1.$n to the number of rows you want. For example, $n = 7 prints from 1 up to 1234567.echo $j . " "; instead of echo $j;.Next: PHP Number Pattern 6
Continue to Program 6 to practice another number pattern using nested loops in PHP.
The total number of printed digits grows like a triangular number. If you print n rows, the total count is 1+2+…+n = n(n+1)/2.
12 people found this page helpful
