Generate Pascal’s Triangle in PHP

Beginner
⏱️ 12 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested loops

What You’ll Learn

Pascal’s triangle is a classic interview warm-up: nested loops, binomial coefficients, and clean printing. This tutorial covers the triangle rule, two generation methods, a live preview, algorithm steps, worked PHP examples, edge cases, and complexity.

Triangle Rule

Edges & neighbors

Every row starts and ends with 1; each inner value is the sum of the two numbers above it.

Binomial C(i, j)

n choose k

Entry at row i, column j equals the binomial coefficient C(i, j).

Multiplicative

In-row update

Update coeff = (int)((coeff * (i - j)) / (j + 1)) to walk a row without factorials.

Additive

Prev-row sums

Build each row from the previous array by adding adjacent neighbors.

Live Preview

1–14 rows

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

O(r²)

Complexity

Both methods print r rows in quadratic time; space differs by approach.

Introduction

Pascal’s triangle starts with a single 1 at the top. Every row begins and ends with 1, and each middle value is the sum of the two numbers directly above it.

In code interviews you are usually asked to print the first r rows with spacing so the triangle looks centered. You can compute values with a multiplicative binomial update, or build each row from the previous one using neighbor sums.

Why it matters?

It trains nested loops, careful indexing, and combinatorics without needing a factorial helper. The same numbers power binomial expansions and many DP warm-ups.

Key Highlights

Rows Grow by One

Row i has i + 1 entries (0-based), always edged with 1.

Binomial Values

Position (i, j) is C(i, j) — useful beyond printing.

Three Patterns

Multiplicative, additive, or return a nested array.

Watch Overflow

Values grow fast; cap deep rows or use BCMath for big coefficients.

In short: print r rows of Pascal’s triangle — edges are 1, insides are neighbor sums (or binomial updates) — and format spacing so the shape reads as a triangle.

📝 Problem & Approach

Given a positive integer rows, print the first rows levels of Pascal’s triangle.

php
// First 5 rows (conceptual shape)
//         1
//       1   1
//     1   2   1
//   1   3   3   1
// 1   4   6   4   1

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle rows to print (must be ≥ 1 for a visible triangle).
Printed outputtextCentered rows of integers with fixed-width spacing.

Minimal workflow

Pseudocode
for i from 0 to rows - 1:
    print leading spaces
    coeff = 1
    for j from 0 to i:
        print coeff
        coeff = coeff * (i - j) / (j + 1)

Method comparison

MethodIdeaExtra space
MultiplicativeUpdate binomial coefficient along the rowO(1)
AdditiveSum neighbors from the previous row listO(rows)

⚡ Quick Reference

GoalPattern
Next binomial in a row$coefficient = (int)(($coefficient * ($i - $j)) / ($j + 1));
Inner cell from previous row$cur[$j] = $prev[$j - 1] + $prev[$j];
Leading spacesecho " "; in a loop
Fixed-width numberecho str_pad((string)$coefficient, 6, " ", STR_PAD_LEFT);
Row lengthRow i has i + 1 values (0-based)

📋 Multiplicative vs Additive vs Factorials

All can print the triangle — but clarity and cost differ.

Multiplicative
in-row update

No factorial calls; compact and O(1) extra space

Additive
prev + prev

Matches the geometric definition; keeps a previous row

n! / (k!(n-k)!)
factorials

Works but slower and easier to get wrong for beginners

Interview tip
explain both

Know the rule first, then pick a clean implementation

Context

When This Problem Shows Up

Reach for Pascal’s triangle drills when nested loops and binomial thinking matter.

  1. Interview warm-ups

    Quick check of loops, indexing, and formatted output.

  2. Combinatorics intro

    Connect printed numbers to C(n, k) without heavy math libraries.

  3. DP precursors

    Additive rows resemble filling a DP table from previous states.

  4. Teaching nested loops

    Outer row loop + inner column loop with a clear visual result.

  5. Not for huge rows alone

    Deep triangles explode in size — cap previews and discuss big integers.

Key benefit: one visual problem that covers loops, math, formatting, and complexity in a short exercise.

🔮 Live Preview

Choose a row count between 1 and 14 and draw the triangle in the browser.

For very deep rows, values get large quickly.

Live result
Press "Draw triangle".

Examples Gallery

Three complete PHP programs — multiplicative update, additive row construction, and a return-an-array variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with clean spacing.

Example 1 — Multiplicative Update

Classic direct coefficient generation for each row — no factorial helper required.

php
<?php
function generatePascalsTriangle(int $rows): void
{
    for ($i = 0; $i < $rows; $i++) {
        $coefficient = 1;

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

        for ($j = 0; $j <= $i; $j++) {
            echo str_pad((string)$coefficient, 6, " ", STR_PAD_LEFT);
            $coefficient = (int)(($coefficient * ($i - $j)) / ($j + 1));
        }

        echo "\n";
    }
}

$numRows = 5;
generatePascalsTriangle($numRows);
?>

How It Works

Each row starts with $coefficient = 1. After printing a value, the next coefficient is updated with (int)(($coefficient * ($i - $j)) / ($j + 1)), which stays exact for binomial rows. Leading spaces keep the triangle centered.

📈 Practical Patterns

Build rows from the geometric definition.

Example 2 — Build Each Row From the Previous

Directly follows the sum-of-two-above definition using arrays.

php
<?php
function generatePascalsTriangleAdditive(int $rows): void
{
    $prev = [];

    for ($i = 0; $i < $rows; $i++) {
        $cur = array_fill(0, $i + 1, 1);
        for ($j = 1; $j < $i; $j++) {
            $cur[$j] = $prev[$j - 1] + $prev[$j];
        }

        for ($s = 0; $s < $rows - $i - 1; $s++) {
            echo "   ";
        }
        foreach ($cur as $value) {
            echo str_pad((string)$value, 6, " ", STR_PAD_LEFT);
        }
        echo "\n";

        $prev = $cur;
    }
}

$numRows = 5;
generatePascalsTriangleAdditive($numRows);
?>

How It Works

Seed $cur as all ones, then overwrite middle cells with $prev[$j - 1] + $prev[$j]. Edges stay 1 automatically. Store $prev = $cur for the next iteration.

📦 Interview Return Shape

Many prompts ask for a nested array instead of printing.

Example 3 — Return an Array of Rows

Build and return the triangle as nested arrays — the common LeetCode-style signature.

php
<?php
function generate(int $numRows): array
{
    if ($numRows < 1) {
        return [];
    }

    $triangle = [];
    for ($i = 0; $i < $numRows; $i++) {
        $row = array_fill(0, $i + 1, 1);
        for ($j = 1; $j < $i; $j++) {
            $row[$j] = $triangle[$i - 1][$j - 1] + $triangle[$i - 1][$j];
        }
        $triangle[] = $row;
    }
    return $triangle;
}

print_r(generate(5));
?>

How It Works

Same additive rule as Example 2, but each finished row is appended to $triangle. Returning data is usually what automated judges expect; printing is for console demos.

🧠 How the Algorithm Prints Rows

1

Loop rows

For row i from 0 to rows - 1, print leading spaces first.

Outer
2

Compute entries

Either update the coefficient formula or sum neighbors from the previous row.

Values
3

Print the row

Output numbers with fixed-width fields, then a newline.

Format
=

Triangle complete

After the last row, the centered Pascal triangle is fully printed.

🔎 Worked Walkthrough — Row i = 4

Trace the multiplicative update for the fifth printed row (0-based i = 4). Start with coeff = 1, then apply coeff = (int)((coeff * (i - j)) / (j + 1)) after each print.

jPrintUpdate after printNext coeff
01(int)((1 * (4 - 0)) / (0 + 1))4
14(int)((4 * (4 - 1)) / (1 + 1))6
26(int)((6 * (4 - 2)) / (2 + 1))4
34(int)((4 * (4 - 3)) / (3 + 1))1
41(row ends)

Printed row: 1   4   6   4   1 — exactly C(4, 0) … C(4, 4).

Use Cases

Where Pascal’s triangle (and its rows) show up beyond the interview prompt.

1. Combinatorics

Read “n choose k” values without writing a factorial helper.

Example: C(5, 2) = 10 from row 5.

2. Binomial Expansion

Coefficients of (a + b)n are exactly row n.

Example: (a+b)³ → 1, 3, 3, 1.

3. DP Warm-Ups

Builds intuition for tabulation from previous states.

Example: each cell depends on two parents above.

4. Pattern / Loop Drills

Nested loops plus formatting practice for beginners.

Example: centered print with fixed-width fields.

5. Probability Basics

Binomial probabilities reuse the same coefficients.

Example: fair-coin paths of length n.

6. Teaching Indexing

Shows why off-by-one bugs appear at triangle edges.

Example: middle loop runs only for 1 .. $i - 1.

Pro Tip: if the interviewer asks for a 2D array, return rows; if they ask to “print the triangle,” prioritize readable spacing after correct values.

Advantages

Why these two generation styles earn interview points.

  1. 1. Multiplicative Is Compact

    Computes a full row with O(1) extra memory and no previous-row storage.

  2. 2. Additive Matches the Definition

    Neighbor sums are easy to explain on a whiteboard from the geometric rule.

  3. 3. No Factorial Needed

    Avoids huge intermediate products from computing n! / (k!(n-k)!) directly.

  4. 4. Exact With Integer Division

    The multiplicative step stays on integers when you cast with (int) correctly.

Pro Tip: lead with the additive story for clarity, then mention the multiplicative update as the space-leaner variant.

Usage Tips

Small habits that keep Pascal code clean in interviews.

  1. 1. Clarify Print vs Return

    Ask whether the judge wants console output or a nested array before writing formatting code.

  2. 2. Keep Edges Implicit

    Initialize rows as all 1s, then fill only middle indices — fewer off-by-one bugs.

  3. 3. Cast Integer Division

    Use (int)((\ldots) / (\ldots)) or intdiv so coefficients stay whole.

  4. 4. Name Rows 0-Based Consistently

    Decide whether row 0 or row 1 is the top, and stick to that in comments and loops.

  5. 5. Format After Correctness

    Get values right first; spacing is polish for human-readable demos.

Pro Tip: dry-run one small row on paper (like i = 4 above) before coding — it catches formula mistakes fast.

Common Pitfalls

Mistakes that commonly break Pascal triangle solutions.

  1. 1. Skipping the (int) Cast

    Float division can yield non-integers and wrong later coefficients.

    → Always cast to int after the multiplicative update.

  2. 2. Off-by-One in the Middle Loop

    Filling 0..$i or 0..$i+1 overwrites edges or skips cells.

    → For additive rows, update only for ($j = 1; $j < $i; $j++).

  3. 3. Mutating the Previous Row In Place

    Editing $prev while reading it corrupts neighbor sums.

    → Build a new $cur array each iteration (or copy carefully).

  4. 4. Factorial Per Cell

    Computing C(n, k) via full factorials is slower and messier than needed.

    → Prefer multiplicative or additive construction.

  5. 5. Ignoring Invalid Row Counts

    $rows ≤ 0 should return empty / error per the prompt — not crash mid-loop.

    → Validate early; for array APIs, return [].

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single cell

Output is just 1 (or [[1]] / a one-row array for return APIs).

rows = 0

Empty triangle

Return [] or print nothing — match the problem statement.

Negative

rows < 0

Treat as invalid; raise or return empty depending on requirements.

Large rows

Big coefficients

PHP ints may overflow; watch print width and limit large r, or use BCMath.

Indexing

0-based vs 1-based

Confirm whether “n rows” means indices 0..n-1 or 1..n.

Width

Fixed field too narrow

Large numbers overflow %6d-style fields — widen or skip centering.

⚖️ Triangle Properties Worth Knowing

Handy facts interviewers sometimes ask as follow-ups.

  • Symmetry. C(n, k) = C(n, n-k), so each row reads the same forwards and backwards.
  • Row sum. The sum of row n (0-based) is 2n.
  • Hockey-stick identity. Partial column sums relate consecutive binomials — useful in proofs, less often in coding interviews.
  • Binomial expansion. Row n is the coefficient list for (a + b)n.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Print only row n

  • Return or print a single row without building unused earlier output formatting
  • Multiplicative update shines here

2. Return nested arrays

  • Match Example 3’s signature
  • Test $numRows in {0, 1, 5}

3. Verify row sums

  • Assert array_sum($row) == 2 ** $i for each generated row
  • Great self-check without looking up answers

4. Left-aligned triangle

  • Drop leading spaces; keep correct values
  • Shows you separate math from formatting

Notes

  • Big numbers. Values grow quickly for large row counts — PHP ints can overflow — limit rows or use BCMath for deep triangles.
  • Cast with (int) after dividing so the multiplicative update stays exact.
  • Validate rows > 0 before printing; rows = 1 should print a single 1.
  • Spacing is cosmetic for interviews — focus first on correct values, then polish alignment.

Quick Takeaway: edges are 1, insides are neighbor sums (or binomial updates), and printing r rows costs O(r²).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Multiplicative methodO(rows²)O(1)
Additive row methodO(rows²)O(rows)
Return array of arraysO(rows²)O(rows²) (stores all cells)
Wrap Up

🎉 Conclusion

Pascal’s triangle is a small nested-loop exercise with big teaching payoff: binomial coefficients, careful indexing, and readable output. Master both the multiplicative update and the additive prev-row approach so you can explain either in an interview.

Practice the three examples above, then continue to perfect numbers for another classic number-theory check.

Edges are 1, insides are neighbor sums — keep the formula exact with (int) division, and validate row counts before printing.

💡 Best Practices

✅ Do

  • Explain the edge/neighbor rule before coding
  • Cast (int) for multiplicative binomial updates
  • Validate rows ≥ 1 (or handle empty output explicitly)
  • Prefer clear spacing over pixel-perfect alignment in interviews
  • State O(r²) time when asked about complexity

❌ Don’t

  • Rely on float division for coefficients
  • Forget leading spaces if the prompt asks for a triangle shape
  • Call factorial for every cell when a O(1) update works
  • Ignore overflow stories in languages with fixed-width ints
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about Pascal’s triangle

Print rows the interview-friendly way.

5
Core concepts
C 02

Binomial

C(i, j) at cell

Math
× 03

Multiplicative

In-row coeff update

Code
+ 04

Additive

Prev-row neighbors

Code
O 05

Complexity

O(r²) time

Analysis

❓ Frequently Asked Questions

It is a triangle of numbers where every inner value equals the sum of the two values above it, and edges are always 1.
It is the number of ways to choose k items from n without caring about order. Entry at row i, column j is C(i, j).
It computes the next value in a row directly without factorial calculations, keeping each step O(1).
Yes — for binomial updates each step lands on an exact integer, so casting with (int) keeps the update exact.
It builds each row from the previous row using the sum of adjacent values — the classic geometric definition.
Printing r rows needs O(r²) time for both methods. Additive uses O(r) extra space; multiplicative can use O(1) extra beyond output.
Build each row as a PHP array, append it to a result array, and return that 2D array. Many interview prompts ask for nested int arrays.
Because C(n, k) = C(n, n-k). The left and right halves of each row mirror each other.

Did you Know? 🔊

Each entry in Pascal’s triangle is a binomial coefficient “n choose k”, which also appears in (a + b)n expansion.

Continue to Perfect Number

Learn how to check whether a number equals the sum of its proper divisors.

Perfect number 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.

8 people found this page helpful