-1

I need to get the average of all the even numbers in this array:

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

Can someone please help me? I'm already trying over an hour.
I have to do it with a for/while loop.

13
  • 1
    sum up the array then divide by the number in the array; it's simple math. Don't they teach math in school now? php.net/manual/en/function.array-sum.php Commented May 13, 2016 at 16:26
  • 1
    Show what you have tried so far. Commented May 13, 2016 at 16:27
  • 1
    Filter out the odd values, and then use sum and divide by the count: $evens = array_filter($aReeks, function ($value) { return $value % 2 == 0; }); $evenAverage = arry_sum($evens) / count($evens); Commented May 13, 2016 at 16:36
  • 1
    @Fred-ii- I still like my answer to that one using the proposed 7.1 piped syntax.... hope one of them submits that as their homework Commented May 13, 2016 at 16:41
  • 1
    possible profile duplicates stackoverflow.com/users/6171058/jari-rengeling - stackoverflow.com/users/6171680/kip-verslaafde Commented May 13, 2016 at 16:41

2 Answers 2

2

Use array_sum() and count()

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

 echo array_sum($Reeks) /count($aReeks);

you can get the array with only the even number this way

 foreach($aReeks as $key => $value) if($key&1) unset($aReeks[$key]);

and then

  echo array_sum($Reeks) /count($aReeks);
Sign up to request clarification or add additional context in comments.

4 Comments

He asked for the average of the even numbers, not just the average.
by even index or even value?
By value... "I need to get the average of all the even numbers in this array:"
I have update the answer
-1
$count = 0;
$average = 0;
foreach ($aReeks as $value)
{
  $count++;
  $average += $value;
}
$average = $average/$count;

echo "average: {$average}<br>";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.