Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to sort an array like this

This is my array:

$arr = array(-3, -4, 1, -1, 2, 4, -2, 3);

I want to sort it like this:

1
2
3
4
-1
-2
-3
-4

So first there would be values greated than zero sorted from the lowest value to the highest value, then there would be negative values sorted from the highest value to the lowest value.

Is there some elegant way to do this?

like image 418
Richard Knop Avatar asked Nov 30 '22 10:11

Richard Knop


1 Answers

Here's a simple comparison function:

function sorter($a, $b) {
    if ($a > 0 && $b > 0) {
        return $a - $b;
    } else {
        return $b - $a;
    }
}

$arr = array(-3, -4, 1, -1, 2, 4, -2, 3);
usort($arr, 'sorter');
var_dump($arr);

Aside: With the above, zero falls on the negative side of the fence. Change the > to >= if you want them to rise to the top of the positive side of said fence.

like image 153
salathe Avatar answered Dec 06 '22 09:12

salathe