Perform Matrix Addition in PHP

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2D lists

What You’ll Learn

Matrix addition combines matching cells: C[i][j] = A[i][j] + B[i][j], only when shapes match. This tutorial covers the rule, nested loops over nested arrays, a live preview, worked PHP examples, edge cases, and complexity.

Definition

Entrywise

Each output cell is the sum of matching input cells.

Same Shape

m × n both

Addition is defined only when dimensions match.

Nested Loops

Rows × cols

Outer loop rows, inner loop columns, visit each cell once.

3×3 Sample

All 10s

Classic demo: complementary matrices sum to 10.

Live Preview

Show sum

Run the 3×3 sample matrices in the browser.

O(m·n)

Per add

Visit each of the m·n cells exactly once.

Introduction

Matrix addition is entrywise: if A and B are both m × n, then C = A + B is also m × n with C[i][j] = A[i][j] + B[i][j].

In PHP interviews, matrices are usually nested arrays. Nested loops walk every position once; if shapes differ, addition is not defined.

Why it matters?

It is the cleanest 2D indexing warm-up — and the foundation before subtraction, multiplication, and transpose problems.

Key Highlights

Same Positions

Top-left adds to top-left — never mix cells.

Shape First

Validate rows and columns before looping.

List of Lists

Access cells with matrix[i][j].

Commutative

A + B = B + A for equal-sized matrices.

In short: if shapes match, walk every cell with nested loops and set C[i][j] = A[i][j] + B[i][j].

📝 Problem & Approach

Given two equal-sized matrices A and B, build C where each cell is the sum of corresponding cells.

php
// [[1, 2], [3, 4]] + [[4, 3], [2, 1]] = [[5, 5], [5, 5]]
// Same shape required; different shape → not defined

Inputs & Outputs

ItemTypeDescription
A, Barray (nested)Two matrices with the same shape.
Return / printmatrix / textResult matrix C with entrywise sums.

Minimal workflow

Pseudocode
function add_matrices(A, B, rows, cols):
    create matrix C of shape rows x cols
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] <- A[i][j] + B[i][j]
    return C

Method comparison

MethodIdeaNotes
Nested loopsC[i][j] = A[i][j] + B[i][j]Interview default — clear indexing
array_map / foreachBuild rows with helpersarray_map style; same O(m·n)
LibrariesA + BProduction speed; show loops in interviews

⚡ Quick Reference

GoalPattern
Rows$rows = count($mat)
Columns$cols = count($mat[0])
Add cell$result[$i][$j] = $a[$i][$j] + $b[$i][$j]
Traversefor ($i = 0; $i < $rows; $i++) for ($j = 0; $j < $cols; $j++)
Print rowecho implode(' ', $row) . PHP_EOL;
Shape checkSame count for rows and each row length

📋 Loops vs array_map vs Libraries

Same entrywise rule — pick the form that fits the interview.

Nested loops
i, j indexing

Clearest story for whiteboards

array_map
map rows

Handy once nested loops are solid

Libraries
A + B

Fast for large data in apps

Interview tip
shape first

State the dimension rule before coding

Context

When This Problem Shows Up

Reach for matrix addition when 2D indexing and entrywise work matter.

  1. Interview warm-ups

    Nested loops plus list-of-lists indexing.

  2. Linear algebra basics

    First matrix operation before multiply / transpose.

  3. Image / grid tasks

    Same pattern as combining equal-sized grids.

  4. After magic numbers

    Shift from digit loops to 2D structures.

  5. Not for multiply

    Different shape rules — do not confuse the two.

Key benefit: one short 2D problem that locks in indexing, shape validation, and O(m·n) thinking.

🔮 Live Preview

Uses the same 3×3 sample matrices as Example 1. Click to display Matrix 1, Matrix 2, and the result.

Matches the sample matrices in code example 1.

Live result
Press “Show 3x3 sum”.

Examples Gallery

Three complete PHP programs — 3×3 helpers, compact 2×2, and a dimension-safe adder. Click View Output to reveal sample console results.

📚 Getting Started

Reusable add and display helpers for a 3×3 pair.

Example 1 — Add Two 3×3 Matrices

Helper functions for addition and display — beginner-friendly and interview-friendly.

php
<?php
function addMatrices(array $mat1, array $mat2): array
{
    $rows = count($mat1);
    $cols = count($mat1[0]);
    $result = [];
    for ($i = 0; $i < $rows; $i++) {
        $row = [];
        for ($j = 0; $j < $cols; $j++) {
            $row[] = $mat1[$i][$j] + $mat2[$i][$j];
        }
        $result[] = $row;
    }
    return $result;
}

function displayMatrix(string $title, array $matrix): void
{
    echo $title . PHP_EOL;
    foreach ($matrix as $row) {
        echo implode(' ', $row) . PHP_EOL;
    }
}

$matrix1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
$matrix2 = [
    [9, 8, 7],
    [6, 5, 4],
    [3, 2, 1],
];

$resultMatrix = addMatrices($matrix1, $matrix2);

displayMatrix("Matrix 1:", $matrix1);
echo PHP_EOL;
displayMatrix("Matrix 2:", $matrix2);
echo PHP_EOL;
displayMatrix("Resultant Matrix:", $resultMatrix);
?>

How It Works

The key line is mat1[i][j] + mat2[i][j]. Nested loops visit every matching position once; the print helper formats each row for the console.

⚡ Compact Size

Same logic on a smaller 2×2 dry-run.

Example 2 — Add Two 2×2 Matrices

Fixed-size loops — great for quick whiteboard checks.

php
<?php
function addMatrices2x2(array $a, array $b): array
{
    $result = [[0, 0], [0, 0]];
    for ($i = 0; $i < 2; $i++) {
        for ($j = 0; $j < 2; $j++) {
            $result[$i][$j] = $a[$i][$j] + $b[$i][$j];
        }
    }
    return $result;
}

function printMatrix(string $title, array $m): void
{
    echo $title . PHP_EOL;
    foreach ($m as $row) {
        echo implode(' ', $row) . PHP_EOL;
    }
}

$a = [
    [1, 2],
    [3, 4],
];
$b = [
    [4, 3],
    [2, 1],
];
$c = addMatrices2x2($a, $b);

printMatrix("A", $a);
echo PHP_EOL;
printMatrix("B", $b);
echo PHP_EOL;
printMatrix("A + B", $c);
?>

How It Works

Even with fixed size 2×2, the pattern is identical: loop over rows and columns and add matching entries.

⚙️ Shape Validation

Reject mismatched or ragged matrices before adding.

Example 3 — Dimension-Safe Adder

Checks empty input, row counts, and uniform column lengths, then adds.

php
<?php
function sameShape(array $a, array $b): bool
{
    if ($a === [] || $b === []) {
        return false;
    }
    if (count($a) !== count($b)) {
        return false;
    }
    $cols = count($a[0]);
    if ($cols === 0) {
        return false;
    }
    foreach (array_merge($a, $b) as $row) {
        if (count($row) !== $cols) {
            return false;
        }
    }
    return true;
}

function addMatricesSafe(array $a, array $b): ?array
{
    if (!sameShape($a, $b)) {
        return null;
    }
    $rows = count($a);
    $cols = count($a[0]);
    $result = [];
    for ($i = 0; $i < $rows; $i++) {
        $row = [];
        for ($j = 0; $j < $cols; $j++) {
            $row[] = $a[$i][$j] + $b[$i][$j];
        }
        $result[] = $row;
    }
    return $result;
}

$ok = addMatricesSafe([[1, 2], [3, 4]], [[4, 3], [2, 1]]);
$bad = addMatricesSafe([[1, 2]], [[1, 2], [3, 4]]);
echo json_encode($ok) . PHP_EOL;
echo json_encode($bad) . PHP_EOL;
?>

How It Works

Shape checks catch mismatched dimensions and ragged rows before any addition. Returning null (or raising) is clearer than silent index errors.

🧠 How the Algorithm Builds C

1

Check dimensions

If row or column counts differ, stop.

Shape
2

Nested traverse

For each i, j set C[i][j] = A[i][j] + B[i][j].

Loops
3

Display result

Print each row on its own line.

Output
=

Sum matrix ready

C has the same shape as A and B.

🔎 Worked Walkthrough — 2×2

Trace each cell for [[1, 2], [3, 4]] + [[4, 3], [2, 1]].

(i, j)ABC
(0, 0)145
(0, 1)235
(1, 0)325
(1, 1)415

Result: [[5, 5], [5, 5]].

Use Cases

Where matrix addition shows up beyond the interview prompt.

1. Interview Warm-Ups

2D indexing with a one-line cell formula.

Example: write addMatrices($A, $B).

2. Teaching Nested Loops

Outer row / inner column with a visual result.

Example: 3×3 all-10s demo.

3. Grid / Image Layers

Combine equal-sized 2D arrays entrywise.

Example: add two intensity maps.

4. Precursor to Multiply

Master shape rules before harder matrix ops.

Example: next up: division / multiply.

5. Validation Habits

Practice rejecting ragged or mismatched shapes.

Example: Example 3 above.

6. Complexity Stories

State O(m·n) when asked about cost.

Example: one add per cell.

Pro Tip: say “same shape, entrywise sum” before writing a single loop.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Simple Formula

    One cell rule: C[i][j] = A[i][j] + B[i][j].

  2. 2. Predictable Cost

    Exactly m·n additions for an m×n pair.

  3. 3. Easy to Dry-Run

    2×2 examples fit on a whiteboard in seconds.

  4. 4. Builds Later Topics

    Same traversal pattern for subtraction and more.

Pro Tip: lead with nested loops; mention array_map helpers only as follow-ups.

Usage Tips

Small habits that keep matrix-addition solutions interview-ready.

  1. 1. State Shape First

    Say “same m×n required” before coding loops.

  2. 2. Build Rows Fresh

    Append a new row list each outer iteration — avoid shared references.

  3. 3. Dry-Run a 2×2

    Four cells catch off-by-one bugs fast.

  4. 4. Print Row by Row

    Keep matrix layout readable in console demos.

  5. 5. Mention O(m·n)

    Interviewers often ask complexity right after the code.

Pro Tip: build each row as a new array; do not reuse one row reference across all rows.

Common Pitfalls

Mistakes that commonly break matrix-addition solutions.

  1. 1. Ignoring Shape Mismatch

    Adding matrices with different sizes.

    → Validate rows and columns first.

  2. 2. Shared Row References

    [[0]*cols]*rows makes every row the same list.

    → Build each row separately (or fill carefully with nested loops).

  3. 3. Ragged Rows

    One row shorter than others raises index errors.

    → Check every row length equals cols.

  4. 4. Swapping i and j

    Wrong index order corrupts rectangular matrices.

    → Keep i = row, j = column consistently.

  5. 5. Confusing With Multiplication

    Using row·column products for addition.

    → Addition is entrywise only.

Edge Cases

Most matrix-addition bugs come from shape assumptions and indexing mistakes.

Shape

Mismatched dimensions

Never add matrices with different row or column counts.

Input

Ragged rows

Validate each row length before indexing.

Index

Wrong loop bounds

Bad ranges skip cells or raise IndexError.

Empty

Empty matrices

Decide whether [] + [] is allowed; guard empty rows.

1×1

Single cell

Still uses the same formula — one addition.

Negatives

Signed entries

Addition works the same for negative integers.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Entrywise. (A+B)ij = Aij + Bij.
  • Commutative. A + B = B + A for equal-sized matrices.
  • Associative. (A + B) + C = A + (B + C) when shapes match.
  • Not multiply. Multiplication has different dimensions and a different formula.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run 2×2

  • Reproduce Example 2 by hand
  • Expect all 5s

2. Shape rejection

  • 2×2 + 2×3 → error / null
  • Assert your guard works

3. array_map rewrite

  • Rewrite add with array helpers
  • Keep the same O(m·n) behavior

4. Subtract next

  • Change + to - with the same loops
  • Warm-up for matrix division page

Notes

  • Definition: C[i][j] = A[i][j] + B[i][j] only when dimensions match.
  • Code pattern: nested loops over rows and columns, plus optional print helper.
  • Complexity: linear in number of cells, m*n.
  • Watch ragged rows and shared-list initialization bugs.

Quick Takeaway: same shape required; add matching cells with nested loops in O(m·n).

⏱️ Time and Space Complexity

OperationTimeExtra space
Add two m × n matricesO(m*n)O(1) besides the output matrix
Print an m × n matrixO(m*n)O(1)
Shape validationO(m) row checksO(1)
Wrap Up

🎉 Conclusion

Matrix addition is entrywise: matching cells add when shapes match. Use nested loops over nested arrays, validate dimensions, and state O(m·n) complexity.

Practice the three examples above, then continue to matrix division for the next 2D operation.

Same shape first, then C[i][j] = A[i][j] + B[i][j] — never confuse this with multiplication.

💡 Best Practices

✅ Do

  • State the shape rule before coding
  • Use nested loops with clear i, j meaning
  • Build each result row as a fresh list
  • Dry-run a 2×2 example
  • Quote O(m*n) complexity

❌ Don’t

  • Add mismatched shapes
  • Initialize with [[0]*cols]*rows
  • Ignore ragged rows
  • Swap row/column indices
  • Confuse addition with multiplication

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix addition

Add matrices the interview-friendly way.

5
Core concepts
= 02

Shape

Same m × n

Constraint
03

Loops

Rows then cols

Code
[] 04

Store

nested array

PHP
O 05

Cost

O(m·n)

Analysis

❓ Frequently Asked Questions

They must have exactly the same dimensions: same row count and same column count. Then each output cell is the sum of matching cells.
For interview-level problems, a matrix is usually a nested array, such as [[1, 2], [3, 4]]. Each inner array is one row.
Yes. For equal-sized matrices, A + B = B + A because each pair of matching entries is added.
For an m x n matrix, we visit each entry once, so time complexity is O(m*n). Extra space is O(1) besides the output matrix.
On 64-bit PHP, int can overflow for huge sums. For interview samples the values stay small; use careful casting if your domain needs big integers.
Because matrices are 2D. The outer loop walks rows and the inner loop walks columns, so every position (i, j) is processed exactly once.
No. Addition is entrywise. Multiplication mixes rows and columns with a different formula and shape rules.
You can map over rows with array functions, but interviews usually want nested for-loops so you show indexing clearly.

Did you Know? 🔊

Matrix addition is entrywise: (A+B)ij = Aij + Bij. It is valid only when both matrices have the same number of rows and columns.

Continue to Matrix Division

Learn how to divide two matrices entrywise with the same nested-loop pattern.

Matrix division 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