JamesBond
JamesBond

Reputation: 312

PHP How to total up the sum from each balance in a foreach loop

code that needs to be totaled up $v['balance']

foreach ($ss['result']['stats'] as $k => $v) {
    print array_sum($v['balance']);
}

the current code prints the following:

0
0.00000938
0.0000007
0.00013408
0.00002358
0.00012234
0.00001106
0.00000159

which is correct. I now want to total up all of them. I have tried multiple different ways and they either display the following:

foreach ($ss['result']['stats'] as $k => $v) {
    print $v['balance']+$v['balance']."<br/>";
}

print

0
1.876E-5
1.42E-6
0.00026816
4.716E-5
0.00025224
2.724E-5
3.18E-6

am I doing something incorrectly ?

Upvotes: 0

Views: 230

Answers (2)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13928

Just use a variable from the outer scope of the iteration.

$total = 0;
foreach ($ss['result']['stats'] as $k => $v) {
    $total += array_sum($v['balance']);
    print array_sum($v['balance']);
}

Upvotes: 1

Adam B
Adam B

Reputation: 165

$total = 0;
foreach ($ss['result']['stats'] as $k => $v) {
     print array_sum($v['balance']);
     $total = $total + $v['balance'];
}

print $total;

Upvotes: 1

Related Questions