- Rule
- Only
a11andb11combine intoc11.
Perform Matrix Addition in PHP
What you’ll learn
- The rule Cij = Aij + Bij for matrices of the same size.
- How to implement add and print helpers with nested
forloops 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]whereiis the row andjis 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.
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.
[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.
- Work
- An
m × nsum needsm·nscalar 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.
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
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]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.
<?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.
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.
<?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
🔄 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.
Mismatched dimensions
Never add A and B with different row or column counts. Validate sizes when reading dynamic input.
Integer ranges
Summing two large int entries can overflow. Use a wider type (long long) if the problem allows huge entries.
Row endings
Print a newline after each row so output matches the usual rectangular layout.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Add two m × n matrices | O(m · n) | O(1) besides the output matrix |
Print an m × n matrix | O(m · n) | O(1) |
Summary
- Definition:
Cij = Aij + Bijfor 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.
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).
8 people found this page helpful
