Jump to content

Sort closest to a declared value


fraser5002

Recommended Posts

Hi ,

 

Is there any simple function in PHP that will allow me to sort an array of numbers base on how close they are to a predifined number

 

say x = 0.1 , 0.4 , 0.6 , 0.7 , 0.8

 

performing a sort on values cloest to 0.5 would give

 

0.4, 0.6 , 0.7 , 0.8, 0.1 ????

 

Is there an easy way to do this in PHP?

Link to comment
https://forums.phpfreaks.com/topic/197619-sort-closest-to-a-declared-value/
Share on other sites

I don't know if there is already a function to do that, but if not then you can write your own. For example:

function doSort($list, $number)
{
$temp = array();
$out = array();

foreach($list as $num)
{
	if($number >= $num)
	{
		$difference = $number - $num;
	}
	elseif($number < $num)
	{
		$difference = $num - $number;
	}

	$temp["$num"] = $difference;
}

asort($temp);

$out = array_keys($temp);

return $out;
}

 

Use it like this, just pass in the array of numbers, and the target number like

 

$list = array(0.1, 0.4, 0.6, 0.7, 0.;

$sorted = doSort($list, 0.5);

print_r($sorted); // prints Array ( [0] => 0.4 [1] => 0.6 [2] => 0.7 [3] => 0.8 [4] => 0.1 ) 

Or use usort/uasort

 

function compare($a, $b) {
  if(abs($a-0.5) > abs($b-0.5)) {
    return 1;
  } 
  if(abs($a-0.5) < abs($b-0.5)) {
    return -1;
  } 
  return 0;
}

usort($array,'compare');

 

and if you have PHP >=5.3 you can use closures for more flexibility:

 

$zeroPoint = 0.5;
usort($array,function($a, $b) {
  if(abs($a-$zeroPoint) > abs($b-$zeroPoint)) {
    return 1;
  } 
  if(abs($a-$zeroPoint) < abs($b-$zeroPoint)) {
    return -1;
  } 
  return 0;
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.