PHP Program to Find Sum of All Matrix Elements
Last Updated :
16 Jul, 2024
Finding the sum of all elements in a matrix is a common operation in mathematical computations and programming. In PHP, this can be achieved using various approaches, including loops and array functions. In this article, we will explore different methods to calculate the sum of all elements in a matrix.
Sum of All Matrix Elements using Nested Loops
This PHP program uses nested loops to find the sum of all elements in a matrix. It iterates through each row and column, adding each element to a running total. The final sum is returned as the result.
Example: Implementation to find the sum of all Matrix elements.
PHP
<?php
function sumMatrixElements($matrix) {
$sum = 0;
foreach ($matrix as $row) {
foreach ($row as $element) {
$sum += $element;
}
}
return $sum;
}
// Driver code
$matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$sum = sumMatrixElements($matrix);
echo "Sum of all matrix elements: $sum";
?>
OutputSum of all matrix elements: 45
Explanation:
- The
sumMatrixElements
function takes a 2D array (matrix) as input. - It uses nested
foreach
loops to iterate through each row and each element in the row. - The elements are accumulated in the
$sum
variable, which is returned at the end.
Sum of All Matrix Elements using Array Functions
This PHP program uses array functions to find the sum of all elements in a matrix. It first flattens the matrix into a single-dimensional array using array_map( ) and array_sum( ), then calculates the sum using array_sum( ).
Example: Implementation to find the sum of all Matrix elements.
PHP
<?php
function sumMatrixElements($matrix) {
return array_sum(array_map("array_sum", $matrix));
}
// Driver code
$matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$sum = sumMatrixElements($matrix);
echo "Sum of all matrix elements: $sum";
?>
OutputSum of all matrix elements: 45
Explanation:
- The
sumMatrixElements
function uses the array_map( )
function to apply array_sum()
to each row of the matrix. This results in an array of row sums. - The
array_sum( )
function is then used again to sum the row sums, resulting in the total sum of all matrix elements.
Using array_reduce and array_merge
This PHP program uses array_reduce and array_merge to find the sum of all elements in a matrix. It first flattens the matrix into a single-dimensional array using array_merge, then calculates the sum using array_reduce.
Example: Implementation to find the sum of all Matrix elements
PHP
<?php
function sumMatrixElements($matrix) {
// Flatten the matrix into a single-dimensional array
$flatArray = call_user_func_array('array_merge', $matrix);
// Calculate the sum of the flattened array
$sum = array_reduce($flatArray, function($carry, $item) {
return $carry + $item;
}, 0);
return $sum;
}
// Driver code
$matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$sum = sumMatrixElements($matrix);
echo "Sum of all matrix elements: $sum";
?>
OutputSum of all matrix elements: 45
Approach 4: Using the array_walk_recursive() Function
The array_walk_recursive() function in PHP can be effectively used to compute the sum of all elements in a multidimensional matrix. This function applies a user-defined callback function to each element of an array recursively, allowing you to operate on arrays of arbitrary depth.
Example: Here's an example that demonstrates how to use array_walk_recursive() to find the sum of all elements in a 2D matrix:
PHP
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$sum = 0; // Initialize sum variable
// Function to sum all elements
array_walk_recursive($matrix, function($value) use (&$sum) {
$sum += $value;
});
echo "The sum of all matrix elements is: $sum";
?>
OutputThe sum of all matrix elements is: 45
Approach 5: Using array_column() and array_sum()
The array_column() function can be used to extract a single column from a multidimensional array. By iterating through the columns of the matrix and summing each column's values using array_sum(), you can find the total sum of all elements in the matrix.
Example
PHP
<?php
function sumMatrixElements($matrix) {
$totalSum = 0;
for ($i = 0; $i < count($matrix[0]); $i++) {
$totalSum += array_sum(array_column($matrix, $i));
}
return $totalSum;
}
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo "The sum of all elements in the matrix is: " . sumMatrixElements($matrix);
?>
OutputThe sum of all elements in the matrix is: 45
Similar Reads
PHP Program to Find the Maximum Element in a Matrix Given a matrix, the task is to find the maximum element of the matrix (arrays of arrays) in PHP. Finding the maximum element in a matrix is a common task that involves iterating through all the elements of the matrix and keeping track of the largest value found. Example: Input: matrix = [ [1, 2, 3],
4 min read
Sum All Elements in a Matrix using R Matrices in R Programming Language are the objects in which the elements are arranged in a 2-D rectangular layout. A matrix is a collection of elements of the same data type(numeric, character, or logical) arranged in a fixed number of rows and columns, as we very well know rows are represented hori
4 min read
How to Calculate Determinant of a Matrix in PHP? Given a Matrix of size M*N, where N and M is an Integer, we need to Calculate calculate of a Matrix in PHP. Example: Input: [[1, 2],[2, 3]]Output: 6Explanation: (1*3)-(2*2)= 6-4= 2 There are several ways to find the determinant of the matrix in PHP which are as follows: Table of Content Using Recurs
4 min read
How to Access and Print Matrix Element at Specific Position in PHP ? Accessing and printing elements at specific positions within a matrix is a fundamental operation in PHP when dealing with two-dimensional arrays. A matrix in PHP can be represented as an array of arrays, where each sub-array represents a row in the matrix. This article explores various approaches to
3 min read
How to get total number of elements used in array in PHP ? In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(arra
2 min read