Repeated Number Triangle in PHP

What You’ll Learn
How to print a repeated number triangle in PHP using nested for loops. Row $i prints the digit $i exactly $i times.
This is a simple way to see how the outer loop controls the digit and the inner loop controls the repetition count.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1
22
333
4444
55555Complete PHP Program
Fixed $n = 5 version:
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $i;
}
echo PHP_EOL;
}🧠 How It Works
Choose the size
$n = 5; sets the number of rows.
Outer loop (digit selection)
for ($i = 1; $i <= $n; $i++) selects which digit to repeat on the row.
Inner loop (repeat $i times)
for ($j = 1; $j <= $i; $j++) repeats echo $i; exactly $i times.
New line
echo PHP_EOL; ends the row and moves to the next line.
Repeated number triangle
The total printed digits are 1+2+…+n = n(n+1)/2, so 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 $i;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Validate input (reject
$n < 1) before printing - Add spaces between numbers (for example,
echo $i . " ";) - Print the descending-row version by counting the outer loop down
- Use a running counter instead of
$ito create Floyd’s triangle - Try printing stars instead of numbers for a star triangle
Avoid
- Forgetting the newline after each row
- Using negative or zero values without validating input
- Printing the wrong variable (this pattern prints
$i, not$j) - Assuming CLI input is always valid (guard
fgets()and casting if needed)
Key Takeaways
The outer loop selects which number to print on the row.
The inner loop controls how many times the number repeats.
Total printed digits follow n(n+1)/2, so runtime is O(n²).
This pattern helps you separate the “value” and the “count” when thinking about loops.
❓ Frequently Asked Questions
$i = 5, the inner loop runs 5 times and prints $i each time.$n to the number of rows you want. The last row will then repeat $n exactly $n times.echo $i; with echo 1; so every row repeats the same digit.Next: PHP Number Pattern 10
Continue to Program 10 for the next number pattern exercise in PHP.
Repeated-digit patterns are a great way to see how one variable can represent the value while another variable represents the repetition count.
12 people found this page helpful
