How to use the array_map In PHP
We are using array_map function that can be used to perform element-wise multiplication and addition. We can apply this function to each row of the first matrix, multiplying it by the second matrix, and then summing the results to get the final matrix.
<?php
function multiplyMatrices($matrix1, $matrix2) {
$result = array_map(function ($row) use ($matrix2) {
return array_map(function ($col) use ($row) {
return array_sum(array_map(function ($a, $b) {
return $a * $b;
}, $row, $col));
}, transpose($matrix2));
}, $matrix1);
return $result;
}
function transpose($matrix) {
return array_map(null, ...$matrix);
}
// Example matrices
$matrix1 = [
[2, 3],
[4, 5],
];
$matrix2 = [
[1, 2],
[3, 4],
];
$result = multiplyMatrices($matrix1, $matrix2);
echo "Matrix 1:\n";
foreach ($matrix1 as $row) {
echo implode(" ", $row) . "\n";
}
echo "\nMatrix 2:\n";
foreach ($matrix2 as $row) {
echo implode(" ", $row) . "\n";
}
echo "\nResult:\n";
foreach ($result as $row) {
echo implode(" ", $row) . "\n";
}
?>
Output
Matrix 1: 2 3 4 5 Matrix 2: 1 2 3 4 Result: 11 16 19 28
How to Find Multiplication of Two Matrices of any Size in PHP?
Multiplying two matrices is a common operation in linear algebra. To multiply two matrices of any size in PHP, you can create a function that takes two matrices as input and returns their product.
Below are the approaches to find the Multiplication of two Matrices of any size in PHP:
Table of Content
- Using nested loops
- Using the array_map