0

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.

2
  • Why not doing everything in a single line, like this: return ceil(array_sum($arr) / count($arr)); ? Commented Feb 9, 2016 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 Commented Feb 10, 2016 at 7:46

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This don't work, i got a null response when have only one item
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/…
0

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

2 Comments

you are actually assigning the array $average = $arr; to variable $average so it should be $average = $arr[0];
and ofcourse there is no need to sort the array, I think! unless you have a specific reason for the same

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.