Repeated Number Triangle Pattern in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Inner loop prints i

What You’ll Learn

The repeated number triangle prints 1, 22, 333, 4444, 55555 — row $i repeats digit $i exactly $i times. This tutorial covers nested-loop logic, live preview, worked PHP examples, edge cases, and O(n²) complexity.

Repeat Digit

echo $i

Row $i prints the digit $i exactly $i times — e.g. row 3 → 333.

Outer Loop

$i = 1..$rows

Outer loop picks the digit for each row — grows from 1 to $rows.

Inner Loop

$j = 1..$i

Inner loop controls repeat count — row length equals outer index $i.

vs Program 5

echo $j vs $i

Program 5 prints ascending digits; this repeats the row digit instead.

Live Preview

1–20 rows

Pick a row count and draw the repeated triangle instantly in the browser.

O(n²)

Complexity

Total digits ≈ n(n+1)/2 — quadratic time; extra memory stays O(1).

Introduction

A repeated number triangle grows each row by one more copy of the same digit: 1, 22, 333, up to 55555 for five rows.

In PHP: outer loop for ($i = 1; $i <= $rows; $i++), inner loop for ($j = 1; $j <= $i; $j++) echo $i, then echo PHP_EOL.

Why it matters?

It teaches the difference between printing loop index $j (Program 5) and repeating row digit $i — then continue to Program 10 for the descending repeat variant.

Key Highlights

echo $i

Inner loop prints the row digit, not $j.

Row length = i

Inner loop runs $i times on row $i.

vs Program 5

Program 5: 1, 12, 123. Program 9: 1, 22, 333.

O(n²)

Total prints grow as n(n+1)/2.

In short: for each $i from 1 to $rows, print $i exactly $i times, then echo PHP_EOL.

📝 Problem & Approach

Given a positive integer $rows (e.g. 5), print a repeated number triangle: row $i repeats digit $i exactly $i times (e.g. row 3 → 333).

PHP
// $rows = 5 (conceptual shape)
for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $i;          // digit i, repeated i times
    }
    echo PHP_EOL;         // next row
}

Inputs & Outputs

ItemTypeDescription
$rowsintNumber of triangle lines — outer loop runs from 1 up to $rows.
$iintOuter loop — current row digit; grows from 1 to rows.
$jintInner loop — runs $j from 1 to $i; prints $i each time.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from 1 up to i:
        print i
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops1, 22, 333, …Learning and interviews
User-input rowsfgets(STDIN);Flexible console programs
Spaced outputecho $i . " "Easier reading per row

⚡ Quick Reference

GoalPattern
Walk rowsfor ($i = 1; $i <= $rows; $i++)
Repeat digit ifor ($j = 1; $j <= $i; $j++) echo $i;
End the rowecho PHP_EOL;
Spaced digitsecho $i . " ";
User inputfgets(STDIN);
Program 5 contrastProgram 5 prints ascending digits (echo $j); Program 9 repeats row digit (echo $i)

📋 Outer Loop vs Inner Loop vs Combined

How outer $i and inner repeat count $j = 1..$i with echo $i work together.

Outer loop
for ($i = 1; $i <= $rows; $i++)

Selects row digit — grows from 1 to rows.

Inner loop
for ($j = 1; $j <= $i; $j++)

Repeats digit $i exactly $i times.

Cell value
echo $i

Print row digit $i each iteration — 333 not 123.

Learning tip
trace i=3

Dry-run when i=3: inner loop runs 3 times → prints 333.

Context

When This Pattern Shows Up

Reach for this pattern when teaching nested loops, growing inner bounds, and concatenated digit output.

  1. After Program 8

    Natural follow-up in the repeat-digit series — compare growing reverse (Program 7/8) with same-digit rows.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible row count.

  4. Gateway to variants

    Compare with Program 5 (ascending digits), then continue to Program 10 (descending repeat triangle).

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Enter a row count and draw the repeated number triangle in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed $rows = 5, fgets(STDIN) input, and a spaced-output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows — inner loop repeats digit $i exactly $i times.

Example 1 — Fixed $rows = 5

Hard-coded row count — outer $i selects the digit; inner $j controls how many times to print it.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $i;
    }
    echo PHP_EOL;
}

How It Works

When $i = 3, the inner loop runs three times and prints $i each time — output 333. When $i = 5, output is 55555.

📈 User Input

Read the row count with fgets(STDIN) instead of hard-coding 5.

Example 2 — User Input Version

Read $rows with fgets(STDIN); same nested loops as Example 1.

PHP
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $i;
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop core as Example 1; only the source of $rows changes.

⚡ Formatting Variant

Add spaces between repeated digits for easier reading.

Example 3 — Spaced Output

Print a space after each repeated digit with echo $i . " ".

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $i . " ";
    }
    echo PHP_EOL;
}

How It Works

Same $j = 1..$i logic with echo $i; only the output format adds spaces between digits.

🧠 How the Algorithm Prints Rows

1

Set up

echo is built in; use fgets(STDIN) when reading input. Set loop variables $i, $j with $rows = 5.

Setup
2

Outer loop walks rows

for ($i = 1; $i <= $rows; $i++) — each row repeats digit $i one more time.

Row
3

Inner loop (j)

for ($j = 1; $j <= $i; $j++) — repeats digit $i exactly $i times.

Inner
4

New line

echo PHP_EOL ends the row after the inner loop finishes.

Break
=

repeated number triangle pattern complete

Each row adds one more copy of the row digit — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — row $i = 3 (when $rows = 5)

Trace how increasing $i adds one more copy of the row digit.

Row $i$j rangeOutput
11..11
21..222
31..3333
41..44444
51..555555

After the inner loop, echo PHP_EOL moves to the next row.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: compare inner bounds with Program 5 and Program 8 and watch digit order change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 10 for the descending repeat triangle.

3. Console Formatting Drills

Practice echo vs echo PHP_EOL without complex math.

Example: put echo PHP_EOL inside the inner loop by mistake.

4. Spaced Output

Add spaces between digits once the two-loop structure works.

Example: use echo $i . " " between digits on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for $rows = 5 — total is still 15 (1+2+3+4+5)).

6. Input Validation Labs

Pair the pattern with fgets(STDIN) return checks and positive-row checks.

Example: reject $rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner PHP courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace $i and $j on paper for $rows = 3 before coding — watch how each row grows by one digit.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Match Inner Bounds

    Outer loop counts down; inner loop must run $j = 1..$i so each row grows on the right.

  2. 2. Prefer fgets(STDIN)

    Call is_numeric($input) so bad input does not leave $rows unset.

  3. 3. Keep echo PHP_EOL Outside

    Only call echo PHP_EOL after the inner loop finishes the row.

  4. 4. Use echo $i for Digits

    for ($j = 1; $j <= $i; $j++) echo $i concatenates digits on one line.

  5. 5. Dry-Run $rows = 3

    Trace $i = 1, 2, 3 on paper before coding the full $rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put echo PHP_EOL inside the inner loop.

Common Pitfalls

Mistakes that commonly break Repeated Number Triangle Pattern patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use echo $i for digits; echo PHP_EOL only after the inner loop.

  2. 2. Printing $j instead of $i

    echo $j builds Program 5’s ascending digits (1, 12, 123) instead of repeated digits (1, 22, 333).

    → Always echo $i inside the inner loop for this pattern.

  3. 3. Wrong inner-loop bound

    Using $j <= $rows on every row prints the same length each time — a rectangle, not a triangle.

    → Keep for ($j = 1; $j <= $i; $j++) so row length equals $i.

  4. 4. Confused with Program 10

    Program 10 repeats digits while counting the outer loop down (5, 44, 333). Program 9 counts up (1, 22, 333).

    → Keep for ($i = 1; $i <= $rows; $i++) for this ascending repeat triangle.

  5. 5. Unchecked fgets(STDIN) input

    Letters or empty input leave $rows unset.

    → Call is_numeric($input) and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit row

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

$rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest triangle

Two rows: 1 and 22.

Bad input

Non-numeric fgets(STDIN) input

Unchecked fgets(STDIN) input leaves $rows unset — call is_numeric($input) first.

Large rows

Large row count

Each row prints $i digits — total work grows as n(n+1)/2.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare Program 5

  • Program 5: ascending 1, 12, 123 (echo $j)
  • Review Program 5

2. Descending repeat variant

  • Reverse outer loop: for (i = rows; i >= 1; i--)
  • See Program 10 — 5, 44, 333, 2222, 11111

3. Next in series

  • Continue with Program 10
  • Descending repeat triangle 5, 44, 333, 2222, 11111

4. Spaced output

  • Use echo $i . " " between digits
  • Same loops, wider visual spacing

Notes

  • Repeat-digit inner loop. Outer loop: $i = 1..$rows. Inner loop: $j = 1..$i with echo $i.
  • echo stays on the line; echo PHP_EOL advances — mix them carefully.
  • Validate $rows > 0 for interactive programs; $rows = 1 should print a single 1.
  • Row $i prints exactly $i copies of digit $i — compare with Program 5 where inner loop prints $j.

Quick Takeaway: outer loop $i = 1..$rows, inner loop $j = 1..$i with echo $i, then echo PHP_EOL.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Spaced output (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The Repeated Number Triangle Pattern is a compact nested-loop lesson: outer loop raises $i while the inner loop echoes digit $i exactly $i times. Master the fixed-$rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 10 for the descending repeating triangle (5, 44, 333, 2222, 11111).

Each row prints digit $i exactly $i times — keep echo $i for digits and echo PHP_EOL for the row break.

💡 Best Practices

✅ Do

  • Use for ($i = 1; $i <= $rows; $i++) in the outer loop
  • Inner: for ($j = 1; $j <= $i; $j++) repeats digit $i
  • Use echo $i for digits and echo PHP_EOL after each row
  • Validate $rows ≥ 1 for interactive programs
  • Call is_numeric($input) before using $rows

❌ Don’t

  • Call echo PHP_EOL inside the inner digit loop
  • Echo $j (Program 5) or reverse the outer loop (Program 10) when you meant repeated ascending digits
  • Forget echo PHP_EOL after each row — the next row continues on the same line
  • Ignore bad console input in user-facing demos
  • Skip the $rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this repeated number triangle pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Repeats digit $i

Code
03

Inner loop

$j = 1..$i, echo $i

Code
04

Newline

Ends each row

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The outer loop sets $i = 4. The inner loop runs $j from 1 to 4 and each iteration echoes $i, so digit 4 appears four times on that row.
The outer loop runs $i from 1 to $rows. For each $i, the inner loop runs $j from 1 to $i and echoes $i, then echo PHP_EOL ends the row.
Reverse the outer loop: for ($i = $rows; $i >= 1; $i--) and keep the inner loop $j = 1..$i with echo $i. That yields 5, 44, 333, 2222, 11111 for five rows — see Program 10.
Program 5 prints ascending digits 1, 12, 123 (echo $j). Program 9 repeats the row digit: 1, 22, 333 (echo $i). Program 10 is the descending repeat triangle (5, 44, 333, 2222, 11111).
Yes. Use echo $i . " " inside the inner loop — see Example 3.
O(n²) for n rows. Total printed digits are 1+2+...+n = n(n+1)/2.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Outer loop sets row digit $i; inner loop prints $i exactly $i times — 1, 22, 333, … O(n²) for $n rows.

Continue to Program 10

Move on to the descending repeating number triangle in the PHP number-pattern series.

Program 10 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful