Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Get sum of each month's sales from two arrays

I have two arrays where the keys are the same, one with the month/year and the other with the values:

Array 1:

['Apr 2023', 'Mar 2023', 'Apr 2023', 'Apr 2023', 'Feb 2023'] 

Array 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[833.00, 223.00, 829.00, 220.00, 498.00]

I need to find the totals for each month:

Apr 2023: 1882.00

Mar 2023: 223.00

Feb 2023: 498.00

I have tried combining into one multidimensional array and then using array_reduce, but I keep getting type errors. I have tried writing a series of functions to step through the data, but I can’t figure out how to compare the month/year with the previous entry. It seems that I’m missing an obvious answer… Any thoughts?
And to those who might say that this has previously been answered multiple times, I have been searching the web and SO for several hours and haven’t come up with anything close.
Thank you!

>Solution :

Iterate over the months array, and use that index to get the amount from the other array, and add that to the month’s sum. Live example at https://3v4l.org/uItTB

<?php

$months = [
    '2023-04',
    '2023-03',
    '2023-04',
    '2023-04',
    '2023-02',
];

$amounts = [
    833,
    223,
    829,
    220,
    498
];

$sums = [];

foreach($months as $i => $month) {
    if (!isset($sums[$month])) {
        $sums[$month] = 0;
    }
    
    $sums[$month] += $amounts[$i];
}

var_dump($sums);

outputs:

array(3) {
  ["2023-04"]=>
  int(1882)
  ["2023-03"]=>
  int(223)
  ["2023-02"]=>
  int(498)
}

Note that the main functionality in the loop is just the line $sums[$month] += $amounts[$i];. The if (!isset($sums[$month])) before that is purely to avoid a PHP warning about the array index being undefined before trying to add a value to it – Warning: Undefined array key "2023-04". You could remove that conditional and it would still function the same. And if you wanted to suppress the warning too, you could use the @ operator: @$sums[$month] += $amounts[$i];.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading