PHP Number Triangle Pattern (Diagonal Fill)

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

What Is This Pattern?

A diagonal-fill number triangle starts each row at index $i, then builds later values with $res = $res + $k where $k begins at $rows − 1 and shrinks.

Remember
Rule: for i = 1..rows
        start with i; k = rows - 1
        next values: res = res + k; k--

1
2 6
3 7 10
4 8 11 13
5 9 12 14 15     ← rows = 5

Unlike Program 54 (space-filled X diamond), here every cell holds a number — filled as if walking down diagonals of a triangle. Program 56 continues with a palindromic number pyramid.

How to Solve It

Print $i first on each row; for later columns add a decreasing step $k. End each row with echo PHP_EOL.

MethodIdeaBest for
Fixed rowsHard-code size; $res + $k stepsLabs and demos
CLI inputSame logic; read $rows at runtimeInteractive practice
Compact rowsimplode without trailing spaceCleaner console output

Pseudocode

Pseudocode
for i from 1 to rows:
    k = rows - 1
    res = i
    for j from i to i+i-1:   // i values
        if i == j: print i and a space
        else:
            res = res + k
            print res and a space
            k = k - 1
    print newline

Cheat sheet

GoalPattern
Set size$rows = 5;
Reset step$k = $rows - 1; each row
First valueif ($i == $j) echo $j . " ";
Next value$res = $res + $k; echo $res . " "; $k--;
Inner spanfor ($j = $i; $j < $i + $i; $j++)
End the rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $j . " " / echo $res . " "Stays on the same lineEach number in the row
echo PHP_EOLEnds the current lineAfter the inner loop finishes

Print values side by side, then break once per row.

Live Preview

Change the row count and the diagonal-fill triangle updates instantly.

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

Live result rows = 5 · values = 15
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15

Worked Walkthrough

Trace $rows = 5, row $i = 3 — how $res and $k build 3 7 10.

Step$jActionPrint
13$i == $j → print start3
24$res = 3 + 4; $k → 37
35$res = 7 + 3; $k → 210

Full row: 3 7 10. Each new row resets $k to $rows − 1 (here 4).

PHP Programs

Three complete programs: fixed $rows = 5, CLI input, and compact implode rows. Use View Output for sample results.

Example 1 — Fixed $rows = 5

Hard-coded size — each row uses $res + $k stepping with $k = $rows - 1.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    $k = $rows - 1;
    $res = $i;

    for ($j = $i; $j < $i + $i; $j++) {
        if ($i == $j) {
            echo $j . " ";
        } else {
            $res = $res + $k;
            echo $res . " ";
            $k--;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Reset each row. Set $k = $rows - 1 and $res = $i before the inner loop.

2. First value. When $i == $j, print the row start ($j).

3. Step and shrink. Otherwise $res = $res + $k, print $res, then $k-- so the next jump is smaller.

Example 2 — User Input

Read $rows from the CLI. Prefer is_numeric (shown below).

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

for ($i = 1; $i <= $rows; $i++) {
    $k = $rows - 1;
    $res = $i;

    for ($j = $i; $j < $i + $i; $j++) {
        if ($i == $j) {
            echo $j . " ";
        } else {
            $res = $res + $k;
            echo $res . " ";
            $k--;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Validate input. is_numeric rejects letters; require a positive whole number.

2. Same stepping. Outer and inner loops match Example 1 — only the source of $rows changes.

3. Scale the step. $k = $rows - 1 automatically matches whatever height the user entered.

Example 3 — Compact Rows

Same logic; use an array and implode to join values without a trailing space.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    $k = $rows - 1;
    $res = $i;
    $parts = [];

    for ($j = $i; $j < $i + $i; $j++) {
        if ($i == $j) {
            $parts[] = $j;
        } else {
            $res = $res + $k;
            $parts[] = $res;
            $k--;
        }
    }
    echo implode(" ", $parts) . PHP_EOL;
}
?>

How It Works

1. Same steps. $res + $k logic is unchanged.

2. Collect, then join. Push each value into $parts, then implode(" ", $parts).

3. No trailing space. Cleaner rows for demos and screenshots.

Edge Cases & Pitfalls

Check these before calling the solution done.

forget k--

Same jump every time

If $k never decreases, every step adds the same offset. Call $k-- after each $res + $k.

k outside

Not resetting $k each row

$k must reset to $rows - 1 at the start of every outer iteration, not once globally.

wrong span

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

That prints only one value per row. The inner loop must run exactly $i times.

rows = 1

Single number

Output is just 1 — a good sanity check.

rows ≤ 0

Empty output

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

PHP_EOL inside

echo PHP_EOL inside the inner loop

That puts each number on its own line. Call echo PHP_EOL only after the row finishes.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Compact implode (Example 3)O(n²)O(1) beyond the row array

Total printed values for n rows: 1 + 2 + … + n = n(n+1)/2.

Key Takeaways

  • Rule: start at $i; then $res = $res + $k with $k decreasing from $rows − 1.
  • Reset: set $k and $res at the start of every outer row.
  • echo vs PHP_EOL: numbers stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 56 builds a palindromic number pyramid.

One line: print $i, then keep adding a shrinking $k to fill the rest of the row.

Frequently Asked Questions

Row 2 starts at 2 (when $i==$j). Next value: $res=2+4=6 because $k starts at $rows-1=4.
$k starts at $rows-1 each row and decreases after each step. It is the offset added to $res for the next number.
With 5 rows you print 1+2+3+4+5=15 numbers total — 15 is the final value on the last row.
Yes. Use a variable $rows and set $k = $rows - 1 at the start of each row.
Exactly $i numbers — the inner loop runs from $j = $i to $j < $i + $i.
Collect values in an array and echo implode(' ', $parts) — see Example 3.
echo $j . " " stays on the same line. echo PHP_EOL ends the row after the inner loop finishes.
O(n²) for n rows because you print n(n+1)/2 numbers in total.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you know?

Each row starts with index $i, then adds decreasing step sizes via $res = $res + $k where $k starts at $rows - 1. Row $i prints exactly $i numbers.

Next: Palindromic Number Pyramid

Continue with rows that climb then fall: 1 2 3 2 1.

Program 56 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