how to get the sum of the values of two array inside an array?

Here is the sample array and I really can't solved it on my own.

I want to add the values of two different array but I really don't know how

enter image description here

Is that possible to add those two values of array??

Here is my sample code that I have used array_sum() but I end up getting only the values(not the sum of the values)

foreach ($_GET['Reservation'] as $key => $value) {
    foreach ($value as $key2 => $value2) {

        foreach ($value2 as $key3 => $value3) {


            echo array_sum($value2);

        }

    }

}

Upvotes: 0

Views: 42

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Within your foreach loop you can simply use + operator, as you don't need array_sum over here. array_sum is used for summation of array and not strings. So your simplified code is as follows

$arr = ['Reservation' => [3=>[56 => [2],57 => [2]],5=>[43 => [1]]]];
$res = '';
$i = 0;
foreach ($arr['Reservation'] as $key => $value) {
    foreach($value as $v)
        $res[$key] += $v[0];
}
print_r($res);

Output:

Array
(
    [3] => 4
    [5] => 1
)

Upvotes: 2

Related Questions