Continuous Number Triangle in PHP

What You’ll Learn
How to print a continuous number triangle in PHP where numbers keep increasing across rows: 1, 2 3, 4 5 6, 7 8 9 10.
We’ll use a counter variable that increments after every print, plus nested loops to control rows and columns.
⭐ Pattern Output
For $rows = 4, the pattern looks like this:
1
2 3
4 5 6
7 8 9 10Complete PHP Program
The counter $k starts at 1 and increments on every print, so the sequence continues across rows.
<?php
$rows = 4;
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $k++ . " ";
}
echo PHP_EOL;
}🧠 How It Works
Initialize the counter
$k = 1; holds the next number to print.
Outer loop (rows)
for ($i = 1; $i <= $rows; $i++) decides how many values each row prints.
Inner loop (print and increment)
Each iteration prints $k and then increments it using $k++, so the next print uses the next integer.
New line per row
echo PHP_EOL; moves to the next row.
Continuous sequence
Because the counter is not reset, numbers continue increasing across rows.
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);
}
$k = 1;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $k++ . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Start from a custom value by setting
$k = 10(or asking the user) - Remove trailing spaces by joining an array of row values
- Print a Floyd’s triangle variant by changing row count and formatting
- Right-align the triangle using leading spaces
- Use
sprintfpadding to align multi-digit numbers in columns
Avoid
- Resetting the counter inside the outer loop (that would restart each row)
- Forgetting the newline after each row
- Skipping input validation for CLI mode
- Assuming single-digit numbers (formatting matters for larger triangles)
Key Takeaways
A single counter outside the loops keeps numbers continuous across rows.
The outer loop controls how many values appear per row (1, 2, 3, ...).
Total numbers printed for r rows is r(r+1)/2.
Formatting becomes important once numbers grow beyond single digits.
❓ Frequently Asked Questions
$k is initialized once and incremented on every print; it is not reset inside the outer loop.printf("%3d ", $k++); to keep columns aligned.Explore More PHP Number Patterns!
Continuous counters are a core pattern in loop problems—try combining them with conditions and alignment.
The triangular number formula \(r(r+1)/2\) tells you exactly how many values are printed for r rows—handy for estimating runtime and output size.
12 people found this page helpful
