- k loop
- Walks the shared dimension and accumulates into
result[i][j].
Perform Matrix Multiplication in PHP
What you’ll learn
- The row × column rule: each entry of
ABis a dot product of a row ofAwith a column ofB. - Why three nested loops appear, and why the result buffer must start at zero before accumulating sums.
- A full 3×3 program matching the classic output, a compact 2×2 second example, and a live preview for the 3×3 case.
Overview
Unlike addition, matrix multiplication combines whole rows with whole columns. The middle dimension must line up: columns of the left factor equal rows of the right factor.
Two programs
3×3 reference matrices and a smaller 2×2 product you can trace by hand.
Live preview
Browser math for the same 3×3 inputs as example 1.
Rigor
Dimension rules, complexity, and contrast with element-wise multiply in the FAQ.
Prerequisites
Nested loops and 2D arrays; comfort with summing products in inner loops.
- Basic PHP arrays, loops, functions, and
echo. - You already know matrix addition (same shape, add cells). Multiplication follows different rules.
What is matrix multiplication?
If A is m × n and B is n × p, then C = AB is m × p. Entry Cij is the sum, over k from 1 to n, of AikBkj.
In code with zero-based indices: C[i][j] collects sum_k A[i][k] * B[k][j].
Formula
For compatible matrices, Cij = ∑k AikBkj. Each output cell is one dot product: row i of A dotted with column j of B.
n × nBoth factors are n × n, so the product is n × n. The reference programs use n = 3 (and n = 2 in the second example).
Trace one cell
For the 3×3 sample, the top-left result entry uses row 0 of the first matrix and column 0 of the second: 1·9 + 2·6 + 3·3 = 30.
Takeaway: the inner index k is where the first matrix’s column index meets the second matrix’s row index.
Live preview
Uses the same 3×3 integer matrices as example 1. Press the button to print both factors and AB.
Algorithm
Goal: compute C = AB for compatible matrices of fixed sizes.
Zero the output
Set every result[i][j] to 0 because you will accumulate sums with +=.
Triple loop
For each i and j, add A[i][k]*B[k][j] for all k in the shared dimension.
Display A, B, and C row by row.
📜 Pseudocode
function multiply(A, B, C, n): // n x n matrices
for i from 0 to n - 1:
for j from 0 to n - 1:
C[i][j] ← 0
for k from 0 to n - 1:
C[i][j] ← C[i][j] + A[i][k] * B[k][j]Multiply two 3×3 matrices
Same matrices and output pattern as the reference: multiply_matrices fills result, display_matrix prints with tabs.
<?php
function multiplyMatrices(array $firstMatrix, array $secondMatrix): array
{
$n = count($firstMatrix);
$result = array_fill(0, $n, array_fill(0, $n, 0));
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
for ($k = 0; $k < $n; $k++) {
$result[$i][$j] += $firstMatrix[$i][$k] * $secondMatrix[$k][$j];
}
}
}
return $result;
}
function displayMatrix(array $matrix): void
{
foreach ($matrix as $row) {
echo implode("\t", $row) . "\n";
}
}
$firstMatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$secondMatrix = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
$resultMatrix = multiplyMatrices($firstMatrix, $secondMatrix);
echo "First Matrix:\n";
displayMatrix($firstMatrix);
echo "\nSecond Matrix:\n";
displayMatrix($secondMatrix);
echo "\nResult Matrix:\n";
displayMatrix($resultMatrix);
?>Explanation
The innermost index k pairs a[i][k] with b[k][j]. Initializing result to zero matters because each result[i][j] is a sum of products.
result[i][j] += a[i][k] * b[k][j];Accumulate. One product per k; repeat for all k to finish cell (i,j).
Smaller 2×2 product (easy to check by hand)
Same triple-loop pattern with N = 2. Top-left output is 1·5 + 2·7 = 19, and so on.
<?php
function multiply2x2(array $a, array $b): array
{
$r = [[0, 0], [0, 0]];
for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
for ($k = 0; $k < 2; $k++) {
$r[$i][$j] += $a[$i][$k] * $b[$k][$j];
}
}
}
return $r;
}
function printMatrix(string $title, array $m): void
{
echo $title . "\n";
foreach ($m as $row) {
echo implode(" ", $row) . "\n";
}
}
$a = [[1, 2], [3, 4]];
$b = [[5, 6], [7, 8]];
$r = multiply2x2($a, $b);
printMatrix("A", $a);
echo "\n";
printMatrix("B", $b);
echo "\n";
printMatrix("AB", $r);
?>Explanation
Combining zero-init with the k loop in one nest is a compact variant; mathematically it matches example 1.
Notes for larger problems
Non-square factors. Generalize loop bounds: i < rowsA, j < colsB, k < colsA (must equal rowsB).
Speed. Researchers use blocked (tile) multiplication and SIMD for huge matrices; interviews usually focus on correct triple loops first.
❓ FAQ
🔄 Input / output
Examples use literals in main. To accept typed input, add nested scanf loops and verify dimensions before multiplying.
Edge cases
Rules that trip beginners:
Inner dimensions
You cannot multiply m×n by p×q unless n = p.
AB vs BA
Matrix multiplication is not commutative in general: AB and BA can differ.
Integer products
Intermediate products may overflow int; consider wider types for big inputs.
⏱️ Time and space complexity
| Setting | Time | Extra space |
|---|---|---|
Two n × n matrices, classic triple loop | O(n3) | O(1) beyond outputs |
m×n by n×p | O(m · n · p) | O(1) beyond outputs |
Summary
- Rule:
Cij = sumk AikBkj; inner sizes ofAandBmust match. - Code: zero
result, then three nested loops with+= a[i][k]*b[k][j]. - Complexity: cubic in
nfor squaren×nmatrices.
Matrix multiplication links rows of A with columns of B. You need A to be m × n and B to be n × p—the two n’s must match—then AB is m × p.
8 people found this page helpful
