Liam Fell
Liam Fell

Reputation: 1320

Get closest value from array up or down

I have the following array with the following function calls:

$monetary_break_points = array( 
                                    10000, 
                                    20000, 
                                    30000,
                                    40000, 
                                );

$lowest_searched =  get_closest(1200,$monetary_break_points,0);
$highest_searched = get_closest(24000,$monetary_break_points,1);

I have the following function:

function get_closest($search, $arr, $sort) {
    if($sort == 1){
        rsort($arr);
    }
    else {
        sort($arr);
    } 

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

The function returns the value from the array $arr that is closest to that which is passed in to it.

However, I need to find the closest value that is less than the value passed in and on occasion and the closest value that is higher than the value passed in, dependent on my needs. Hence the third parameter in the function, if I want to find the closest higher value I rsort the array. This should in theory return the closest higher number, however it does in fact return the closest lower number though. Could anyone suggest why?

$lowest_searched is set to 1000, which is correct.

$highest_searched is set to 20000, which is incorrect, it should be 30000.

Upvotes: 0

Views: 109

Answers (1)

Aniket
Aniket

Reputation: 129

$monetary_break_points = array( 
                                    10000, 
                                    20000, 
                                    30000,
                                    40000, 
                                );

echo '<br/><br/>lowest_searched'.$lowest_searched =  get_closest(1200,$monetary_break_points,0);
echo '<br/>highest_searched'.$highest_searched = get_closest(24000,$monetary_break_points,1);

function get_closest($search, $arr, $sort) {
    if($sort == 1){
        rsort($arr);
    }
    else {
        sort($arr);
    } 

   $closest = null;
   foreach ($arr as $item) {
       if($sort == 0)
       {
        if ($closest === null || abs($search - $closest) > abs($item - $search)) {
             $closest = $item;
        }
       }

       if($sort == 1)
       {
           if($search < $item )
               $closest = $item;
       }       
   }
   return $closest;
}

Upvotes: 1

Related Questions