jdawg
jdawg

Reputation: 558

Sort array by the distance to a number

For example if you have a set of numbers 5,4,3,2,1 and you want all numbers ordered by closest to 3 the result would be 3,2,4,5,1.

I've tried using uasort and written a custom sort function to take the fixed digit(3 in this case), but it didn't work. I wrote the function to take the fixed digit away from the current two digits being compared and applied abs to them.

I need a way where I can compare which number of comparing how close the current number being accessed is and to slot it in the right place in the array.

Any ideas? Can this be achieved using uasort?

Upvotes: 6

Views: 737

Answers (1)

Rizier123
Rizier123

Reputation: 59691

uasort() is already a good start. Now you just have to use the distance to 3 as criteria to sort your array:

number   | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
---------------------------------------
distance | 3 | 2 | 1 | 0 | 1 | 2 | 3 | 

Code:

uasort($arr, function($a, $b){
    return abs(3-$a) - abs(3-$b);
});

Upvotes: 9

Related Questions