-1

For example say there is a numeric array (let's assume it's k sorted already) keyed by unix timestamps with integer values.

$array = [
    312345678 => 1,
    312345692 => 4,
    312345703 => 33,
    .... etc.
];

and you needed an array sum of all the values from unix time 310284763 (which may or may not be a key in the array) to 338672926 (which may or may not be a key in the array).

Obviously you could do something unperformative like:

$total = 0;
foreach($array as $time => $value){
    if($time < $min){continue;}
    if($time > $max){break;}
    $total += $value;
}

But is there a nice way of extracting a "range" of a numeric array?

jamesgarrett
  • 101
  • 6
  • 2
    James, I find your requirements to be clear, but please offer a concrete [mcve] (no ellipsis) with exact desired output. (for the record, I think your way is sufficiently optimized, concise, and readable) Where does this data come from? SQL? – mickmackusa Jun 03 '22 at 07:39
  • How many entries are we talking about here? How large is the array (before the max key)? Are you actually noticing performance issues with the posted code specifically, or is it just an assumption that it's not good enough? – M. Eriksson Jun 03 '22 at 07:42
  • Let's say the array is 10000 values long, but for every single item you have to generate a rolling total adding up the previous 7 days. – jamesgarrett Jun 03 '22 at 07:45
  • Yes this is a job for sql i think, nevertheless, the question is can it be done with an array in PHP. – jamesgarrett Jun 03 '22 at 07:47
  • 1
    Well, I guess you could try your luck at searching for exact starting key with `isset()`. You could also try [systematically guessing the location of the qualifying start key](https://stackoverflow.com/q/21954489/2943403). But all of that seems clunky and ugly. I recommend enjoying the tools that SQL offers -- `WHERE`, `GROUP BY`, `SUM`. – mickmackusa Jun 03 '22 at 08:05
  • No faster way than a single loop to get the sum here. Period. – nice_dev Jun 03 '22 at 09:03

0 Answers0