 Tags  # How to Sum values in array by key indexes in loop

By : Leapepe
Date : May 03 2020, 08:17 AM

I try  sum some values from the array from certain ranges provided by another array.

I've tried with the following function :

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

and this works if i hard code the numbers,

but i can't figure out how to make this to work in a loop

So I have this array named dates

``````array(3) {
["June"]=> int(4)
["July"]=> int(31)
["August"]=> int(29)
}
``````

and i have this  array named daily_values

``````array(64) {
=> int(8)
=> int(6)
=> int(10)
=> int(15)
=> int(10)
=> int(9)
=> int(9)
.
.
.
 => int(10)
``````

Now I want to do here is: based on how many entries are in for example

June which is 4 in this case I want to get the sum of values in daily_values array like this:

first loop iteration will sum values in daily_values array from 0 to 3, the second loop iteration will sum values from 4 to 34 and third loop iteration will sum values from 35 to 63 and so on and so on.

and I want from all this is to have an array which will be like this

`["sum of 0,3", "sum of 4,34", "sum of 35,63"]`

Just a note here, this array is much bigger, but I cut it short just for question purposes. Answer :

try the Following code :

I created a same test and it works good for me. Hope it helps you in someway.

``````<?php

\$june = [1,1,1,1];
\$july = [1,1];
\$august = [1,1,1,1];

\$months = array(
'June' => \$june,
'July' => \$july,
'August' => \$august,
);

\$daily = [1,1,1,1,5,5,10,10,10,10,2,2,2,2,2];
\$sum_arr = array();

\$i = 0;
foreach(\$months as \$key=>\$month){

\$month_count = \$month;
\$month_sum = 0;
while(\$month_count > 0){
\$month_sum += \$daily[\$i];
\$i++;
\$month_count--;
}
\$sum_arr[\$key] = \$month_sum;
}

echo '<pre>';
print_r(\$sum_arr);

?>`````` Related Posts : 