Perform Matrix Subtraction in PHP

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

What you’ll learn

  • The element-wise rule Cij = Aij − Bij for matrices of the same size.
  • A complete 3×3 program (including negative differences), a compact 2×2 variant, and a live preview.
  • How subtraction relates to addition (A − B = A + (−B)) and common interview follow-ups.

Overview

Subtracting matrices works like subtracting numbers in a table: the top-left result uses the top-left of A minus the top-left of B, and so on for every cell.

Two programs

3×3 reference data and a 2×2 difference.

Live preview

Same integers as example 1; prints A, B, and A − B.

Negatives

Expect negative entries whenever B exceeds A in a cell.

Prerequisites

Same as matrix addition: nested loops and 2D arrays.

  • Basic PHP arrays, loops, functions, and echo.
  • Signed integers can be negative; subtraction produces negatives naturally.

What is matrix subtraction?

For matrices A and B with the same shape, C = A − B is defined by Cij = Aij − Bij for every row i and column j.

Equivalently, subtracting B is adding (−B) entrywise.

Order A − B
Reverse B − A = −(A − B)

Live preview

Uses the same 3×3 inputs as example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.

Matches the sample matrices in code example 1.

Live result
Press “Show 3×3 difference”.

Algorithm

Goal: compute C[i][j] = A[i][j] - B[i][j] for all cells.

Same shape

A and B must share row and column counts.

Subtract per cell

Nested loops over i and j; assign the difference to result[i][j].

Print

Optional helper to print each row on its own line.

📜 Pseudocode

Pseudocode
function subtract_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

Subtract two 3×3 matrices (program with explanation)

subtract_matrices computes matrix1 − matrix2. Values match the reference walkthrough (differences can be negative).

c
<?php
function subtractMatrices(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("\t", $row) . "\n";
    }
}

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

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

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

Explanation

Each result[i][j] is one subtraction. Tab spacing keeps columns readable in the terminal.

2

Subtract two 2×2 matrices

Same pattern with #define ROWS / COLS; useful when an interviewer asks for a smaller trace-by-hand example.

c
<?php
function subtract2x2(array $a, array $b): array
{
    $out = [[0, 0], [0, 0]];
    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 = subtract2x2($a, $b);

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

Explanation

Here 1 - 4 = -3 and 4 - 1 = 3 show negatives and positives in one small grid.

Notes

In place. You could write differences back into one array only if you no longer need the original operand stored there.

Unsigned types. Avoid unsigned for differences if negatives are possible.

❓ FAQ

Subtraction works cell by cell like addition: same position in A minus same position in B. Matrix multiplication combines rows of A with columns of B and is a different operation entirely.
Yes. Each entry of A - B needs a matching entry in B, so both must be m x n for the same m and n.
Usually no. Subtraction is not commutative: B - A is the negative of A - B entrywise.
Yes. If A[i][j] < B[i][j], the difference at that cell is negative. int stores negatives fine within range.
Subtracting two large ints can still overflow signed int in edge cases. Use wider types if inputs can be huge.
Each of the m*n entries is computed once: O(m*n) time and O(1) extra space besides the output matrix.

🔄 Input / output

Programs above embed matrices in source. Interactive versions would read values with scanf after checking dimensions.

Edge cases

Most issues match matrix addition: wrong sizes or numeric range.

Shape

Mismatched matrices

Subtraction needs identical dimensions, same as addition.

Range

int overflow

Very large magnitudes can overflow when subtracting; consider wider integer types.

⏱️ Time and space complexity

OperationTimeExtra space
Subtract two m × n matricesO(m · n)O(1) besides result storage

Summary

  • Definition: C = A − B with Cij = Aij − Bij; same shape required.
  • Code: nested loops; each cell is one subtraction.
  • Relation: A − B = A + (−B) entrywise.
Did you know?

Matrix subtraction is entrywise like addition: (A − B)ij = Aij − Bij. It is the same as adding A and (−B). The two matrices must have the same shape.

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