0
"accounts" => array:6 [
    0 => array:2 [
      "acc_id" => 1
      "balance" => 1000.00
    ]
    1 => array:2 [
      "acc_id" => 2
      "balance" => -1500.00
    ]
    2 => array:4 [
      "acc_id" => 3
      "balance" => 5000.00
    ]
]

Hi, How could I sum up all the balance correct?

Code

foreach ($y['accounts'] as $k) 
{
    $sum_balance = $k['balance'];           
}
$sum_balance += $sum_balance;

With this code, The result will only sum the last balance itself. Example result is 10000.00

1
  • 1
    you are overwriting $sum_balance with every iteration of the loop, then double it after the loop. just go through your code line by line and actively try to understand what it is doing. Commented Apr 14, 2019 at 11:30

3 Answers 3

3

You need to increment sum in the foreach loop:

$sum_balance = 0;
foreach ($y['accounts'] as $k) 
{
    $sum_balance += $k['balance'];           
}
var_dump($sum_balance);
Sign up to request clarification or add additional context in comments.

Comments

3

combine array_sum() with array_column()

array_column()

Return the values from a single column in the input array

array_sum()

Calculate the sum of values in an array

$y = [
    'accounts' => [
        0 => [
          "acc_id" => 1,
          "balance" => 1000.00
        ],
        1 => [
          "acc_id" => 2,
          "balance" => -1500.00
        ],
        2 => [
          "acc_id" => 3,
          "balance" => 5000.00
        ]
    ]
];

var_dump(
    array_sum(array_column($y['accounts'], 'balance'))
);


result:float 4500

2 Comments

You might want to add some explanation for the OP and future readers.
It would be better if you matched OPs data structure, in which case you would want array_sum(array_column($y['accounts'], 'balance'));
1

Your solution is almost correct, just initialize the $sum_balance before the loop and sum it inside the loop.

$sum_balance=0;
foreach ($y['accounts'] as $k) 
{
    $sum_balance += $k['balance'];           
}

Hope it helps, if you need any help feel free to connect.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.