-1

I have 3 percentile values calculated that are stored in variables like this:

$twentyfive = '55';
$fifty = '80';
$seventyfive = '95';

Each user on my website has a value from 20-100 stored in the variable: $percentile and I am trying to match their number closest to one of the three variables above so I can say: You are part of the X percentile.

For example, if a users $percentile value was '35' they would be matched with $twentyfive since that's the closest variable to their number.

Any help would be appreciated

Saveen
  • 4,120
  • 14
  • 38
  • 41
Brayden
  • 125
  • 3
  • 14
  • 2
    You are expected to try to **write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard May 14 '19 at 18:33
  • What will the range for giving the user these percentiles? Like $twentyfive : 20 to ?, $fifty : ? to ? So on – ShivCK May 14 '19 at 18:41

3 Answers3

0
if($percentile < 67.5){
   echo $twentyfive
}  elseif($percentile > 67.5 && $percentile < 87.7){
   echo $fifty
}else{
   echo $seventyfive
}
Valentino
  • 7,291
  • 6
  • 18
  • 34
0

If the values of the 3 variables can change you can use this. There may be a more concise way, but this should work.

//Set users percentile
$user_percentile = 35;
$user_percentile_category = 25;

switch ($user_percentile) {
    case $user_percentile <= $twentyfive:
        $user_percentile_category = '25';
        break;
    case ($user_percentile - $twentyfive) < $fifty - $user_percentile:
        $user_percentile_category = '25';
        break;
    case ($user_percentile - $twentyfive) >= $fifty - $user_percentile:
        $user_percentile_category = '50';
        break;
    case ($user_percentile - $fifty) < $seventyfive - $user_percentile:
        $user_percentile_category = '50';
        break;
    case ($user_percentile - $fifty) >= $seventyfive - $user_percentile:
        $user_percentile_category = '75';
        break;
    default:
        $user_percentile_category = '75';
}
PhxSteve
  • 103
  • 1
  • 13
0

You can use below code for this:

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

$collection = [55,80,95];
$searchValue = 88;

echo getClosest($searchValue, $collection);

Hope it helps you. I have taken the reference from Find a matching or closest value in an array

Cheers!!

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18