Skip to content
Advertisement

How can I sort an array stating in a given number

First of all I am new in php. I need help to sort an array.

I have an array of ID’s and zip codes like this:

Array (
    [2286] => 3150-259 
    [2284] => 3040-256 
    [2282] => 5430-659 
    [2280] => 2560-270 
    [2278] => 3740-271 
    [2276] => 2495-401 ... and so on 
)

Now I have a number lets say ‘2900’ I would like to sort my array from the closest number (2900) to the most distant.

Example: the number is 2900. So the array should sort like this:

Array (
   [2284] => 3040-256 
   [2286] => 3150-259 
   [2280] => 2560-270 
   [2276] => 2495-401 
   [2282] => 5430-659 ... and so on

Can someone help me?

Thank you

Advertisement

Answer

I guess, you can use function uksort in next way:

<?php
$arr = [
    2286 => "3150-259",
    2284 => "3040-256",
    2282 => "5430-659",
    2280 => "2560-270",
    2278 => "3740-271",
    2276 => "2495-401",
];

$n = 2900;

uksort($arr, function ($a, $b) use ($n) {
    return (abs($a-$n) >= abs($b-$n)) ? 1 : -1;
});

var_export($arr);

Check PHP code here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement