Open In App

PHP Program to Find Sum of All Matrix Elements

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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";
  
?>


Output

Sum 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";
  
?>


Output

Sum 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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads