There is the following code that fills the matrix with random number and displays its elements:

<?php $sum_col = 0; for ($i = 1; $i <= 5; $i++) { $sum_row = 0; for ($j = 1; $j <= 7; $j++) { $matrix[$i][$j] = rand(-100, 100); $sum_row = $sum_row + $matrix[$i][$j]; echo $matrix[$i][$j] . ' '; if ($j == 7) echo $sum_row . '</br>'; } } ?> 

The sum of the elements in the rows of the matrix is ​​calculated correctly. I can’t figure out how to calculate and display the sum of the elements in the columns in the last line.

  • one
    IMHO, there is no logic at all. First, the matrix must be generated, and then you can perform operations on it. - Indifferent
  • I thought about it. Then I decided that in order to calculate the amounts, I don’t need to add as much code, and decided to mix everything up. As a result, he himself was confused)). I will rewrite. - co11ter

1 answer 1

Not sure what a good option, but it is not difficult to finish :)

 <?php for ($i=1; $i<=5; $i++) { $sum_row=0; for($j=1; $j<=7; $j++) { $matrix[$i][$j]=rand(-100, 100); $sum_row=$sum_row+$matrix[$i][$j]; echo $matrix[$i][$j].' '; if ($j==7) echo $sum_row.'</br>'; } } for ($i=1; $i<=7; $i++) { $sum_col=0; for($j=1; $j<=5; $j++) { $sum_col=$sum_col+$matrix[$j][$i]; } echo $sum_col.' '; } ?>