Skip to content
Advertisement

PHP – array_key_exist return true then push a new element into element itself [closed]

I have a two array based on my query;

The first array:

$payments = [
    'IDR' => [
        17 => '0.00'
        18 => '100000.00'
        19 => '400000.00'
    ]
]

Then this is the second array:

$advance = [
    'IDR' => [
        17 => '100000.00'
        19 => '0.00'
    ]
    'USD' => [
        18 => '7.00'
    ]
]      

I need to manipulate those array into the format like this :

$payments = [
    'IDR' => '500000.00',
    'USD' => '0'
]

$advance = [
    'IDR' => '100000.00',
    'USD' => '7.00'
]

So the final result is simple as like :

$result = [
     'IDR' => '400000.00',
     'USD' => '-7.00'
]

I think i need array_key_exist to check in each array have IDR and USD in payment also array_sum ? Any advise it so appreciated.

Advertisement

Answer

First you’ll need to make sure you have a unique union of all keys available in both arrays:

$currencies = array_unique(array_merge(
    array_keys($payments), 
    array_keys($advance)
));

With this in place you can now sum the values while iterating over each currency:

$result = [];

foreach ($currencies as $currency) {
    // Note that a currency might not be available in either payment or advance,
    // so we need to provide an empty array as fallback in each array_sum.
    $payments[$currency] = array_sum($payments[$currency] ?? []);
    $advance[$currency] = array_sum($advance[$currency] ?? []);

    $result[$currency] =  $payments[$currency] - $advance[$currency];
}

$payments, $advance and $result now contain your expected data.

Of course other loop structures such as array_map, array_walk, array_reduce are also possible. I just chose for foreach for the sake of readability.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement