0

I have a array and i need to get the average of all the EVEN numbers in the array i already have tried this but it still doesn't work.

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 
for ($q = 0; $q < count($aReeks); $q++)
      {
          { 
            if ($aReeks[$q] % 2 == 0)
            $totaaleven = array_sum($aReeks[$q]) / count($aReeks[$q]);
          }
      }
echo $totaaleven
5
  • What's with the weird inner block? also, you need a ; after echo $totaleven Commented May 13, 2016 at 18:12
  • 2
    Can't you figure it out from the answers given to all your previous questions this afternoon? Like stackoverflow.com/questions/37212309/… and stackoverflow.com/questions/37210893/… Commented May 13, 2016 at 18:15
  • 1
    $totaaleven = array_sum($even = array_filter($aReeks,function($v) {return $v%2==0;}))/count($even); No (explicit) looping required... Commented May 13, 2016 at 18:15
  • I have to do it with a loop Commented May 13, 2016 at 18:15
  • 3
    I hope that your teacher appreciates that we're beginning to get fed up with you and the number of your fellow students who have been asking exactly the same questions all afternoon; especially as every question is just a minor variation on the others.... the max value, the average, the sum, etc Commented May 13, 2016 at 18:18

2 Answers 2

3

I think this should work for you

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 

$evenSum = 0;
$evenCount = 0;

foreach($aReeks as $number) {
    if($number % 2 == 0) {
        $evenSum = $evenSum + $number;
        $evenCount++;
    }
}

$average = $evenSum / $evenCount;
Sign up to request clarification or add additional context in comments.

Comments

2

You can filter your array using array_filter for even number, and simply divide sum with count, see below:

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 
$evenNos = array_filter($aReeks, function($value) {
    return !($value%2);
});
echo array_sum($evenNos)/count($evenNos);

Comments

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.