-4

I have a problem to sum the values ​​using foreach. enter image description here

I want to add the value of 12000 to 11000 but the result is only 11000, which is the last data.

$no = 1;
foreach ($record->result_array() as $calc) {
    $sum = 0;
    $sum += $calc['harga_jual'] - $calc['diskon'];
    $no++;
}
Axel Köhler
  • 911
  • 1
  • 8
  • 34
mas K
  • 1
  • Welcome to SO. Could you please read https://stackoverflow.com/help/how-to-ask and edit your question ? (At a minimum, you should add some code that could be reproduced, not an image and this little sample of code, if you want to have a chance that someone helps you) – Rivers Feb 04 '21 at 12:39
  • Does this answer your question? [How does PHP 'foreach' actually work?](https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work) – Muhammad Usman Feb 04 '21 at 20:35

2 Answers2

3

The initialization of variable $sum ...is meant to be outside the foreach loop ...

That is $sum = 0 is meant to be outside the foreach loop ...

1

Note:- The declaration & initialization of $sum = 0; is outside the foreach loop.

<?php 
    
    $sum = 0;
    foreach ($record->result_array() as $calc) 
    {
       $sum += $calc['harga_jual'] - $calc['diskon'];
    }
    echo $sum;
    ?>
KUMAR
  • 1,993
  • 2
  • 9
  • 26