An 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 as follows:

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

So, first there will be values ​​generated than zero, sorted from the lowest value to the highest value, then there will be negative values ​​sorted from the highest value to the lowest value.

Is there an elegant way to do this?

+4
source share
5 answers

Here the method is not usort() , if we accept zero, it does not matter ...

 <?php $arr = array(-3, -4, 1, -1, 2, 4, -2, 3); $positive = array_filter($arr, function($x) { return $x > 0; }); $negative = array_filter($arr, function($x) { return $x < 0; }); sort($positive); rsort($negative); $sorted = array_merge($positive, $negative); print_r($sorted); ?> 

EDIT: no PHP 5.3? Use create_function() as you say:

 $positive = array_filter($arr, create_function('$x', 'return $x > 0;')); $negative = array_filter($arr, create_function('$x', 'return $x < 0;')); 
+6
source

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); 

In addition to this: zero falls on the negative side of the fence. Change > to >= if you want them to rise on the upper side of the positive side of the mentioned fence.

+10
source

usort () can sort anything with your own set of rules
dunno if it matches your aesthetic feelings.

+2
source

I'm sure this can be made shorter, but this works:

 <?php function cmp($a, $b) { if ($a == $b) return 0; if($a>=0 && $b>=0 ) return ($a < $b) ? -1 : 1; if( $a<=0 && $b<=0) return (-$a < -$b) ? -1 : 1; if($a>0) return -1; return 1; } $a = array(-3, -4, 1, -1, 2, 4, -2, 3); var_dump($a); usort($a, "cmp"); var_dump($a); ?> 

Working link.

+2
source

The best algorithm I got is:

  if ((a >= 0) == (b >= 0)) { return a - b; } else { return b - a; } 

This will sort the negative numbers from the end of the array (e.g. splicing)

0
source

All Articles