Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

How to find the sum of each row and each column of a matrix (2D array) in PHP

2 Answers

0 votes
$arr = array(     
             array(1, 2, 3, 5),  
             array(4, 5, 6, 5),  
             array(7, 8, 9, 5)  
           );  
   
$rows = count($arr);  
$cols = count($arr[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";
}  
   
for ($i = 0; $i < $cols; $i++) {  
    $sumCol = 0;  
    for ($j = 0; $j < $rows; $j++) {  
      $sumCol = $sumCol + $arr[$j][$i];  
    }  
    echo "Sum of col " . $i . " = " . $sumCol . "\n"; 
}  




/*
run:

Sum of row 0 = 11
Sum of row 1 = 20
Sum of row 2 = 29
Sum of col 0 = 12
Sum of col 1 = 15
Sum of col 2 = 18
Sum of col 3 = 15

*/

 





answered Feb 21, 2021 by avibootz
edited Feb 21, 2021 by avibootz
0 votes
$arr = array(     
             array(1, 2, 3, 5),  
             array(4, 5, 6, 5),  
             array(7, 8, 9, 5)  
           );  
    
$rows = count($arr);  
$cols = count($arr[0]);  
    
for ($i = 0; $i < $rows; $i++) {  
    echo "Sum of row " . $i . " = " . array_sum($arr[$i]) . "\n";
}  
    
for ($i = 0; $i < $cols; $i++) {  
    echo "Sum of col " . $i . " = " . array_sum(array_column($arr, $i)) . "\n"; 
}  
 
 
 
 
/*
run:
 
Sum of row 0 = 11
Sum of row 1 = 20
Sum of row 2 = 29
Sum of col 0 = 12
Sum of col 1 = 15
Sum of col 2 = 18
Sum of col 3 = 15
 
*/

 





answered Jun 23, 2023 by avibootz
...