Perform Matrix Addition in PHP

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
2D arrays

What you’ll learn

  • The rule Cij = Aij + Bij for matrices of the same size.
  • How to implement add and print helpers with nested for loops over rows and columns.
  • Two complete programs: a classic 3×3 demo and a smaller 2×2 variant, plus a browser live preview for the 3×3 sample.

Overview

Matrix addition is the entry-by-entry sum of two matrices of identical shape. In PHP you typically represent each matrix as a nested array and fill the result with nested loops.

Two programs

The reference 3×3 sample and a compact 2×2 illustration.

Live preview

Runs the same arithmetic as the first program on the built-in sample matrices.

Rigor

Shape rules, complexity, and realistic interview follow-ups in the FAQ.

Prerequisites

Arrays, nested loops, and formatted output with echo.

  • Basic PHP arrays and function syntax.
  • Comfortable indexing with M[i][j] where i is the row and j is the column.

What is matrix addition?

If A and B are both m × n matrices, their sum C is the m × n matrix with Cij = Aij + Bij for every valid row i and column j.

If the shapes differ, addition is not defined in ordinary linear algebra—your program should either require matching dimensions or report an error.

Same shape add entrywise
Different shape not defined

Formal definition

If A and B are both m × n matrices (same row and column counts), then C = A + B satisfies Cij = Aij + Bij for all valid i and j. The same entrywise rule applies to integer matrices.

2×2 example

[1 2; 3 4] + [4 3; 2 1] = [5 5; 5 5] — each position adds independently.

Intuition

Think of each cell as one independent slot: you never mix entries from different positions.

a11+b11 Top-left
Rule
Only a11 and b11 combine into c11.
m·n Adds
Work
An m × n sum needs m·n scalar additions.

Takeaway: nested loops simply schedule those m·n additions in row-major (or any fixed) order.

Live preview

Uses the same 3×3 integers as the first PHP program below. Press the button to print Matrix 1, Matrix 2, and the sum.

Matches the sample matrices in code example 1.

Live result
Press “Show 3×3 sum”.

Algorithm

Goal: given two matrices A and B of the same dimensions, produce C with C[i][j] = A[i][j] + B[i][j].

Confirm shape

Fixed-size arrays already encode matching dimensions. For dynamic sizes, verify row and column counts before adding.

Nested traversal

For each row index i and column index j, assign result[i][j] = mat1[i][j] + mat2[i][j].

Display (optional)

Print rows with spaces or tabs between entries and a newline after each row.

📜 Pseudocode

Pseudocode
function add_matrices(A, B, C, rows, cols):
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] ← A[i][j] + B[i][j]
1

Add two 3×3 matrices (program with explanation)

Classic interview layout: add_matrices fills the result, display_matrix prints any 3×3 grid. Sample data matches the reference walkthrough.

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

function displayMatrix(array $matrix): void
{
    foreach ($matrix as $row) {
        echo implode(' ', $row) . "\n";
    }
}

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

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

echo "Matrix 1:\n";
displayMatrix($matrix1);
echo "\nMatrix 2:\n";
displayMatrix($matrix2);
echo "\nResultant Matrix:\n";
displayMatrix($resultMatrix);
?>

Explanation

The core is result[i][j] = mat1[i][j] + mat2[i][j] inside the nested loops. display_matrix walks the same indices but prints instead of assigning.

for ($i = 0; $i < 3; $i++) for ($j = 0; $j < 3; $j++)

Row-major visit. Each pair (i,j) is handled exactly once.

echo implode(' ', $row)

Spacing. A space after each entry keeps columns aligned in simple console output.

2

Add two 2×2 matrices

Same pattern with smaller arrays: useful when an interviewer asks you to generalize dimensions verbally before fixing them at 3.

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

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

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

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

Explanation

ROWS and COLS make it obvious where to change sizes later; the arithmetic inside the loops is unchanged.

Optimization and extensions

Large matrices. For many entries (m · n large), memory bandwidth dominates; cache-friendly traversal (row-major for row-major storage) helps. Parallel threads can partition rows when correctness rules allow.

General size. Pass rows and cols as parameters (and preferably use a single flat buffer plus strides if you need variable shapes in one binary).

Interview: start with the double loop and correct indexing; mention shape checks and complexity when asked.

❓ FAQ

They must have the same dimensions: the same number of rows and the same number of columns. Then each entry of the sum is the sum of the corresponding entries.
The usual interview approach is a 2D array, for example int A[ROWS][COLS], or a flat array with manual indexing i * COLS + j for row-major layout.
Yes: A + B = B + A entrywise. Associativity (A + B) + C = A + (B + C) holds as well.
Same shape requirement: C_ij = A_ij - B_ij. It is equivalent to adding A and (-B).
For an m×n matrix, adding two matrices touches each element once: O(m·n) time and O(1) extra space aside from storing the result.
You need to visit every row index i and column index j to compute result[i][j] = mat1[i][j] + mat2[i][j]. Two loops (outer rows, inner columns) match that traversal.

🔄 Input / output notes

The first program uses compile-time matrices. For interactive input you would add nested scanf loops (or read from a file) before calling add_matrices, still checking that both inputs share the same dimensions.

Edge cases and pitfalls

Most bugs are indexing and type issues, not the addition formula itself.

Shape

Mismatched dimensions

Never add A and B with different row or column counts. Validate sizes when reading dynamic input.

Overflow

Integer ranges

Summing two large int entries can overflow. Use a wider type (long long) if the problem allows huge entries.

Print

Row endings

Print a newline after each row so output matches the usual rectangular layout.

⏱️ 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)

Summary

  • Definition: Cij = Aij + Bij for all positions; shapes must match.
  • Code: nested loops over rows and columns; optional separate routine to print.
  • Complexity: linear in the number of entries m · n.
Did you know?

Addition of real matrices is entrywise: (A+B)ij = Aij + Bij. It is only defined when A and B share the same shape (same row and column counts).

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