PHP Number Triangle Pattern (Fill with N)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A fill-with-n number triangle prints an ascending run from the row start to $n, then pads with $n so every row has the same width.

Remember
Rule: for i = n..1, print i..n then pad with n (i-1 times)

5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5     ← n = 5

In PHP two inner loops do the work: sequence ($j from $i to $n) then fill ($n printed $i - 1 times), then echo PHP_EOL ends the row. Program 20 continues with a continuous counter across rows.

How to Solve It

Outer loop counts down from $n to 1. First inner loop prints $i..$n. Second inner loop pads with $n. End each row with echo PHP_EOL.

MethodIdeaBest for
Sequence + fillPrint $i..$n, then pad with $nLearning, interviews, exams
Custom fillPad with a separate constantWhen the fill value should differ from $n

Pseudocode

Pseudocode
for i from n down to 1:
    for j from i to n:
        print j and a space
    for j from 1 to i - 1:
        print n and a space
    print newline

Cheat sheet

GoalPattern
Outer (descend)for ($i = $n; $i >= 1; $i--)
Sequencefor ($j = $i; $j <= $n; $j++) echo $j . " ";
Fill padfor ($j = 1; $j < $i; $j++) echo $n . " ";
End the rowecho PHP_EOL;
Custom fillPrint $fill instead of $n in the second loop

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $j . " "Stays on the same lineEach number in the row
echo PHP_EOLEnds the current lineAfter both inner loops

Print all numbers without a newline, then end the row once.

Live Preview

Change the width n and the fill-with-n triangle updates instantly.

Whole numbers from 1 to 12. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · 5 rows · 25 numbers
5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5

Worked Walkthrough

Trace three outer values when $n = 5 — watch the sequence grow and the fill count shrink.

$iSequenceFill countPrinted row
5545 5 5 5 5
33 4 523 4 5 5 5
11 2 3 4 501 2 3 4 5

Every row prints exactly n numbers, so total work is n × n = n².

PHP Programs

Three complete programs: fixed $n = 5, CLI input, and a custom fill constant. Use View Output for sample results.

Example 1 — Fixed $n = 5

Hard-coded width — sequence loop first, then pad with $n.

PHP
<?php
$n = 5;

for ($i = $n; $i >= 1; $i--) {
    for ($j = $i; $j <= $n; $j++) {
        echo $j . " ";
    }
    for ($j = 1; $j < $i; $j++) {
        echo $n . " ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Outer loop descends. $i runs from $n down to 1 — top row is mostly fill; bottom is the full sequence.

2. Sequence run. Print $j from $i to $n.

3. Pad to width. Print $n exactly $i - 1 times so the row length stays $n.

Example 2 — Width Input

Read $n from the CLI. Prefer is_numeric in real apps (shown in the tip below).

PHP
<?php
echo "Enter the triangle width: ";
$n = (int) trim(fgets(STDIN));

for ($i = $n; $i >= 1; $i--) {
    for ($j = $i; $j <= $n; $j++) {
        echo $j . " ";
    }
    for ($j = 1; $j < $i; $j++) {
        echo $n . " ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Prompt and read. Ask for a width, then trim(fgets(STDIN)) and cast to int.

2. Same two-loop core. Both the sequence end bound and the fill value use $n.

3. Safer input tip. Bare (int) casts turn letters into 0. Prefer:

Safer input
echo "Enter the triangle width: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 1) {
    echo "Enter a positive whole number." . PHP_EOL;
    exit(1);
}
$n = (int) $input;

Example 3 — Custom Fill Constant

Pad with $fill = 9 while the sequence still runs up to $n = 5.

PHP
<?php
$n = 5;
$fill = 9;

for ($i = $n; $i >= 1; $i--) {
    for ($j = $i; $j <= $n; $j++) {
        echo $j . " ";
    }
    for ($j = 1; $j < $i; $j++) {
        echo $fill . " ";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Same sequence. The first inner loop still prints $i..$n.

2. Different pad. The second loop prints $fill instead of $n.

3. Same width. Each row still has exactly $n numbers.

Edge Cases & Pitfalls

Check these before calling the solution done.

missing fill

Forgetting the second inner loop

Rows become jagged. Keep the pad loop so every row has width $n.

wrong fill count

$j <= $i instead of $j < $i

That prints one extra pad. Use for ($j = 1; $j < $i; $j++) for exactly $i - 1 fills.

PHP_EOL inside

echo PHP_EOL inside an inner loop

That puts each number on its own line. Call echo PHP_EOL only after both inner loops finish.

n = 1

Single number

Output is just 1 — a good sanity check.

n ≤ 0

Empty output

The outer loop never runs. Validate and prompt again for clearer UX.

spaces

Keep the trailing space

The classic sample uses echo $j . " " so numbers stay spaced and readable.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input / custom fill (Examples 1–3)O(n²)O(1)

There are n rows printing n numbers each, so total work is n².

Key Takeaways

  • Rule: for $i = n..1, print $i..$n, then pad with $n exactly $i - 1 times.
  • Two loops: sequence grows as you go down; fill shrinks by one each row.
  • echo vs PHP_EOL: numbers stay on the line; echo PHP_EOL advances after both inner loops.
  • Next step: Program 20 prints a continuous counter across growing rows.

One line: descend $i from $n, print $i..$n, pad with $n, then echo PHP_EOL.

Frequently Asked Questions

When $i = 5, the sequence loop prints $j = 5 once, then the fill loop runs 4 times — all values are 5, so the row is 5 5 5 5 5.
The first inner loop prints the increasing sequence $i..$n. The second fills remaining positions with $n so every row has the same width.
When $i = 1, the sequence loop prints $j = 1 to 5 and the fill loop runs zero times — no padding needed.
echo $j . " " stays on the same line with a trailing space. echo PHP_EOL ends the current line. Numbers use echo; the row break uses echo PHP_EOL after both inner loops.
Replace n in the second loop with a separate fill constant — Example 3 on this page pads with 9 while the sequence still runs to 5.
Rows will have different widths — the top row may be short while the bottom row is full length.
O(n²) for width n because each of n rows prints n numbers.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int so bad input does not produce unexpected results.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you know?

Each row prints an ascending sequence $i..$n, then pads with $n so every row has width $n. The second inner loop runs $i - 1 times — still O(n²) total prints.

Next: Continuous Number Triangle

Continue with a counter that keeps climbing across growing rows.

Program 20 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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