Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
    
Why not doing everything in a single line, like this: return ceil(array_sum($arr) / count($arr)); ? – Rajdeep Paul Feb 9 at 14:33
    
You're right, I'm usually do all the operation line per line, so anyone can understand who is doing, your expression surely more correct – andreaem Feb 10 at 7:46

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;
}
share|improve this answer
    
you are actually assigning the array $average = $arr; to variable $average so it should be $average = $arr[0]; – Saurabh Sinha Feb 9 at 14:32
2  
and ofcourse there is no need to sort the array, I think! unless you have a specific reason for the same – Saurabh Sinha Feb 9 at 14:33

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;
}
share|improve this answer
    
This don't work, i got a null response when have only one item – andreaem Feb 10 at 9:13
    
It works for me. What version of PHP are you running? Can you show the data you're testing to see if there's something else weird happening? Demo: sandbox.onlinephpfunctions.com/code/… – Gary Feb 10 at 13:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.