andreaem
andreaem

Reputation: 1655

PHP: Calculate average value of an array if have more than one element

I must to calculate the value of an array taken from a query only if had more than one element, else I must to return the value of the element, I'm using this code:

function calculate_average($arr) {
  if (count($arr) === 1) {
    $average = $arr;
  } else {
    sort($arr);
    $count = count($arr); //count items in array
    $sum = array_sum($arr); //sum of numbers in array
    $median = $sum / $count; //divide sum by count
    $average = ceil($median); //convert number in excess value
  }
   return $average;
}

And work when there is two or more value, but return NULL when there is only one value, why?

Thanks to all who want to partecipate.

Upvotes: 0

Views: 2015

Answers (2)

Gary
Gary

Reputation: 13912

As it's been said, to do it the way you're trying to, you need to access the first element of your array like

$average = $arr[0];

However, your method of calculating the average will still work for an array with one element. It'll just work out to x/1.

function calculate_average($arr) {
  $count = count($arr); //count items in array
  $sum = array_sum($arr); //sum of numbers in array
  $median = $sum / $count; //divide sum by count
  $average = ceil($median); //round number

  return $average;
}

Upvotes: 1

Kumar Saurabh Sinha
Kumar Saurabh Sinha

Reputation: 870

Please try this:

function calculate_average($arr) {
  if (count($arr) === 1) {
    $average = $arr[0];
  } else {
    sort($arr);
    $count = count($arr); //count items in array
    $sum = array_sum($arr); //sum of numbers in array
    $median = $sum / $count; //divide sum by count
    $average = ceil($median); //convert number in excess value
  }
   return $average;
}

Upvotes: 0

Related Questions