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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With