0

I have an foreach loop that takes some values from a MySQL database. The foreach it's very simple but with about 100 rows, like:

foreach($values as $value){}

what i'm trying to do but i don't know how it's to make inside the foreach the average of the previous 5 rows. So starting from the 5th row to do the average of the rows 1-5 then on the row 6 to do the average of rows 2-6 etc.


later edit, an simple example ex:

$values = array(1,2,3,4,5,6,7,8,9,10);
$i = 0;
foreach($values as $value){
if $i > 5{$average = (1+2+3+4+5)/5 }
// and here continue like if $i = 6 {$average = (2+3+4+5+6)/5}
// if $i = 7 {$average = (3+4+5+6+7)/5}
$i++;
}
3
  • 2
    Can you please elaborate more or show us an example of the expected outcome? Commented Oct 25, 2014 at 9:22
  • what do you want the result to look like.. an array with averages Commented Oct 25, 2014 at 9:26
  • i've made a simple example Commented Oct 25, 2014 at 9:31

3 Answers 3

3
$total = 0;
foreach ($values as $i => $value) {
    $total += $value;
    if ($i >= 5) {
        $total -= $values[$i-5]; // Remove the oldest row
        $count = 5;
    } else {
        $count = $i+1;
    }
    $average = $total/$count;
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's getting a bit late here (Australia) but I think something along the lines of.

$avg = array();
$averages = array();
$i = 0;
foreach($values as $value){
    $i++;
    echo $value;
    if($i <= 5){
        $avg[] = $value;
    }else{
        $calc = 0;
        foreach($avg as $a){
             $calc = $calc + $a;
        }
        $averages = $calc / 5;
    }
}

print_r($averages);

Comments

1

You can use array_slice() for slice and array_sum() to calculate total then average. An example here

$values = array(1,2,3,4,5,6,7,8,9,10);
foreach($values as $k=>$v){
    if($k > 4){
       echo $ave = array_sum(array_slice($values, $k - 5, $k)) / 5 . '<br />';
    }
}

1 Comment

I think he wants running averages. This breaks the array up into separate groups of 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.