How to find the total sum of matrix rows in PHP

2 Answers

0 votes
$arr = array(     
             array(1, 2, 3, 5),  
             array(4, 5, 6, 1),  
             array(7, 8, 9, 3)  
           );  
    
$rows = count($arr);  
$cols = count($arr[0]);  

$total = 0;

for ($i = 0; $i < $rows; $i++) {  
    $sumRow = 0;  
    for ($j = 0; $j < $cols; $j++) {  
      $sumRow = $sumRow + $arr[$i][$j];  
    }  
    
    echo "Sum of row " . $i . " = " . $sumRow . "\n";
    $total += $sumRow;
}

echo "Total = " . $total . "\n";



/*
run:

Sum of row 0 = 11
Sum of row 1 = 16
Sum of row 2 = 27
Total = 54

*/

 



answered Jun 10, 2024 by avibootz
0 votes
function total_sum_of_matrix_rows($matrix) {
    $rows = count($matrix);  
    $cols = count($matrix[0]);  
     
    $total = 0;
     
    for ($i = 0; $i < $rows; $i++) {  
        $sumRow = 0;  
        for ($j = 0; $j < $cols; $j++) {  
          $sumRow = $sumRow + $matrix[$i][$j];  
        }  
         
        echo "Sum of row " . $i . " = " . $sumRow . "\n";
        
        $total += $sumRow;
    }
    
    return $total;
}

$matrix = array(     
             array(1, 2, 3, 5),  
             array(4, 5, 6, 1),  
             array(7, 8, 9, 3)  
           );  

echo "Total = " . total_sum_of_matrix_rows($matrix). "\n";
 
 
 
/*
run:
 
Sum of row 0 = 11
Sum of row 1 = 16
Sum of row 2 = 27
Total = 54
 
*/

 



answered Jun 12, 2024 by avibootz

Related questions

...