Perform Matrix Subtraction in PHP
What you’ll learn
- The element-wise rule
Cij = Aij − Bijfor 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.
Live preview
Uses the same 3×3 inputs as example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.
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].
Optional helper to print each row on its own line.
📜 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]Subtract two 3×3 matrices (program with explanation)
subtract_matrices computes matrix1 − matrix2. Values match the reference walkthrough (differences can be negative).
<?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.
Subtract two 2×2 matrices
Same pattern with #define ROWS / COLS; useful when an interviewer asks for a smaller trace-by-hand example.
<?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
🔄 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.
Mismatched matrices
Subtraction needs identical dimensions, same as addition.
int overflow
Very large magnitudes can overflow when subtracting; consider wider integer types.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Subtract two m × n matrices | O(m · n) | O(1) besides result storage |
Summary
- Definition:
C = A − BwithCij = Aij − Bij; same shape required. - Code: nested loops; each cell is one subtraction.
- Relation:
A − B = A + (−B)entrywise.
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.
8 people found this page helpful
