0

Out of a variable number of values I need to calculate the average. The challenge: The average can only be one of the following fixed values (the closest!):

$allowedAverageValues = [0.66, 1, 1.33, 1.66, 2]

I calculate the average as follows:

$randomValues = [1.33, 1, 0.66, 1, 2, 1.33];
$average = array_sum($randomValues)/count($randomValues); // returns 1.22

How can I identify the value in $allowedAverageValues that is closest to $average? So the desired result is 1.33.

Kent Miller
  • 499
  • 2
  • 8
  • 21
  • 1
    Wouldn't it make more sense to use a median for this case? – Dormilich Dec 12 '18 at 13:18
  • 2
    Possible duplicate of https://stackoverflow.com/questions/5464919/find-a-matching-or-closest-value-in-an-array – misorude Dec 12 '18 at 13:21
  • (Duplicate easily found by googling “php find closest numeric value” - that the value is an average in this particular case, doesn’t change the solution one bit, and therefor neither what you should have researched to begin with …) – misorude Dec 12 '18 at 13:23
  • 1
    Possible duplicate of [Find a matching or closest value in an array](https://stackoverflow.com/questions/5464919/find-a-matching-or-closest-value-in-an-array) – DEarTh Dec 12 '18 at 13:31

2 Answers2

0

I think this is what you're looking for :

<?php
function getClosest($search, $arr) {
   $closest = null;
   foreach ($arr as $item) {
      if ($closest === null || abs($search - $closest) > abs($item - $search)) {
         $closest = $item;
      }
   }
   return $closest;
}

$randomValues = [1.33, 1, 0.66, 1, 2, 1.33];
$average = array_sum($randomValues)/count($randomValues); // returns 1.22
$res = getClosest($average, $randomValues);

print_r($res); // returns 1.33

Function from the first answer Find a matching or closest value in an array

executable
  • 3,365
  • 6
  • 24
  • 52
0
$arr = [0.66, 1, 1.33, 1.66, 2];

function getNearest($arr,$var){
    usort($arr, function($a,$b) use ($var){

        return  abs($a - $var) - abs($b - $var);
    });
   return array_shift($arr);
}

$randomV = [1.33, 1, 0.66, 1, 2, 1.33];
$ave = array_sum($randomV)/count($randomV); 
$res = getNearest($ave, $randomV);

print_r($res);
sr_shubh
  • 31
  • 5