PHP Matrix Subtraction Program

Beginner
5 min read
Updated: Oct 2026
2 programs
Live preview

What Is Matrix Subtraction?

Matrix subtraction subtracts matching cells: C[i][j] = A[i][j] - B[i][j]. Both matrices must have the same number of rows and columns.

Remember
A − B is defined only when A and B have the same shape

  [ 9  8 ]   [ 1  5 ]   [ 8  3 ]
  [ 7  6 ] − [ 4  2 ] = [ 3  4 ]

Rule: (A − B)[i][j] = A[i][j] − B[i][j]

Negatives are allowed (e.g. 2 − 5 = −3).
PositionABA − B
[0][0]918
[0][1]853
[1][0]743
[1][1]624

How to Subtract Matrices in PHP

Four clear steps — same nested loops as addition, with minus.

  1. Confirm both matrices have the same rows and columns.
  2. Create a result matrix of that same size.
  3. Outer loop walks rows; inner loop walks columns.
  4. Set $result[$i][$j] = $a[$i][$j] - $b[$i][$j] for every cell.
MethodIdeaTimeBest for
Nested loopsSubtract matching cells into a new arrayO(m × n)Interviews, teaching
Shape-safe subtractValidate count first, then subtractO(m × n)Safer production-style code

Pseudocode

Pseudocode
function SubtractMatrices(A, B):
    rows = rows of A
    cols = cols of A

    if rows != rows of B or cols != cols of B:
        error "shapes must match"

    C = new matrix[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]

    return C

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
RuleC[i][j] = A[i][j] - B[i][j]
RequirementSame rows and same columns
Rows / colscount($a) / count($a[0])
NegativesAllowed and expected when B > A
Vs multiplySubtraction is entrywise only
Classic check[[9,8],[7,6]] − [[1,5],[4,2]] = [[8,3],[3,4]]

Live Preview

Pick a sample pair to see matrices A, B, and A − B.

Tap a chip to run. Results may include negative numbers.

Result
A =
9  8
7  6

B =
1  5
4  2

A − B =
8  3
3  4

Worked Walkthrough — 2×2

Visit every index once and subtract the matching cells.

Calculation
A = [9 8]    B = [1 5]
    [7 6]        [4 2]

i=0, j=0 → 9 − 1 = 8
i=0, j=1 → 8 − 5 = 3
i=1, j=0 → 7 − 4 = 3
i=1, j=1 → 6 − 2 = 4

Result = [8 3]
         [3 4]

PHP Programs

Start with a clear nested-loop subtractor. Then add a shape check so mismatched sizes fail safely.

Example 1 — Nested Loops

Subtract two same-sized nested arrays cell by cell and print the result.

php
<?php
function subtractMatrices($a, $b) {
    $rows = count($a);
    $cols = count($a[0]);
    $result = [];

    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            $result[$i][$j] = $a[$i][$j] - $b[$i][$j];
        }
    }
    return $result;
}

function printMatrix($m) {
    foreach ($m as $row) {
        echo implode(" ", $row) . "\n";
    }
}

$a = [[9, 8], [7, 6]];
$b = [[1, 5], [4, 2]];
printMatrix(subtractMatrices($a, $b));
?>

How It Works

  1. Read rows and columns with count($a) and count($a[0]).
  2. Build a result array of the same size.
  3. Outer loop chooses row $i; inner loop chooses column $j.
  4. Store $a[$i][$j] - $b[$i][$j] into $result[$i][$j].
  5. Print walks the result the same way — one row per line.

Example 2 — Shape-Safe Subtract

Validate dimensions before subtracting so mismatched matrices fail with a clear error.

php
<?php
function subtractMatrices($a, $b) {
    $rows = count($a);
    $cols = count($a[0]);

    if (count($b) !== $rows || count($b[0]) !== $cols) {
        throw new InvalidArgumentException("Matrices must have the same dimensions.");
    }

    $result = [];
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            $result[$i][$j] = $a[$i][$j] - $b[$i][$j];
        }
    }
    return $result;
}

$a = [[10, 9, 8], [7, 6, 5]];
$b = [[1, 2, 3], [4, 5, 6]];
$diff = subtractMatrices($a, $b);

foreach ($diff as $row) {
    echo implode(" ", $row) . "\n";
}
?>

How It Works

  1. Compare both row counts and column counts.
  2. Throw if shapes differ — subtraction would be undefined.
  3. Otherwise run the same nested-loop subtraction as Example 1.
  4. For the 2×3 sample: 5 - 6 = -1 shows negatives are fine.
  5. Mention the shape check in interviews even when samples already match.

Edge Cases & Pitfalls

Check these before calling the solution done.

Shape

Must match

Different sizes cannot be subtracted — validate first.

Negatives

Expected

When $b[$i][$j] > $a[$i][$j], the cell is negative.

Order

A − B ≠ B − A

Subtraction is not commutative — keep the operand order clear.

Multiply

Different problem

Do not confuse entrywise subtract with row-column multiply.

Time and Space Complexity

ProgramTimeExtra space
Nested loopsO(m × n)O(1) besides result
Shape-safe subtractO(m × n)O(1) besides result

Every cell is touched exactly once. The result matrix needs O(m × n) space to store the answer.

Key Takeaways

  • Rule: subtract matching cells; shapes must match.
  • Loops: outer rows, inner columns.
  • Negatives: valid when B’s cell is larger.
  • Test: [[9,8],[7,6]] − [[1,5],[4,2]] → [[8,3],[3,4]].

One line: same shape required — then C[i][j] = A[i][j] − B[i][j].

Frequently Asked Questions

Only when they have the same dimensions — same row count and same column count. Then each result cell is A[i][j] − B[i][j].
Yes. If B’s cell is larger than A’s, the difference is negative. That is normal.
No. Subtraction is entrywise for same-sized matrices. Multiplication uses row-column dot products and different shape rules.
A − B is the same idea as A + (−B). Both need matching shapes and nested loops over every cell.
For an m × n matrix, each entry is visited once, so time is O(m × n).

Next: Matrix Transpose

Swap rows and columns of a matrix in PHP.

Matrix transpose 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.

8 people found this page helpful