-3
//input array
$array = {
          2 => 5,
          4 => 1,
          8 => 3,
          9 => 2,
}

want sum of key for a specific period like 1-5, 6-10

need output like array {1-5 => 6 ,6-10 => 5}

without using foreah

YasirPoongadan
  • 563
  • 4
  • 17
  • You're aware that the code you have written is not even a valid PHP array right? If you want to use the shorthand syntax it is square brackets `[]` not curly braces `{}` and will only work for PHP 5.4.X and above. – Mike Nov 20 '13 at 18:32
  • i need a code, that not use foreach – YasirPoongadan Nov 20 '13 at 18:35
  • Related question: [PHP sum all values of a numeric array between min and max two keys performatively](https://stackoverflow.com/q/72486200/2943403) – mickmackusa Jun 03 '22 at 07:46

1 Answers1

3

Try this code.. Not a rocket science..

function sumArray($array, $min, $max) {
   $sum = 0;
   foreach ($array as $k => $a) {
      if ($k >= $min && $k <= $max) {
         $sum += $a;
      }
   }
   return $sum;
}

echo sumArray($array, 1, 5);
zzlalani
  • 21,360
  • 16
  • 42
  • 72