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.

Answers


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;
}

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;
}

Need Your Help

HTTPS requests and multi-threading

java url connection connection-pooling

Is Java's URL class a thread-safe, in particular [URL.openConnection()](http://java.sun.com/javase/6/docs/api/java/net/URL.html#openConnection())?

DIV with text over an image on hover

javascript css user-interface image

OKay first off this is really really similiar to the http://dribbble.com homepage.