1

I want to sort only those values in array which are not 0 and all 0 values key should be at bottom. so for example if our array is like this-

array
{
    [0]=>4
    [1]=>0
    [2]=>2
    [3]=>0
    [4]=>3
}

So sorted array I should get like below

array
{
    [2]=>2
    [4]=>3
    [0]=>4
    [1]=>0
    [3]=>0
}
gmsantos
  • 1,332
  • 19
  • 28
TECHNOMAN
  • 351
  • 1
  • 9
  • 2
    And what did you tried so far? – vaso123 Jan 23 '15 at 10:31
  • 2
    Remove the zeroes using [`array_filter()`](http://php.net/manual/en/function.array-filter.php) (and count them), [sort](http://php.net/manual/en/function.sort.php) the remaining, append the removed zeroes to the end. – axiac Jan 23 '15 at 10:35

4 Answers4

5

Use uasort() function:

$arr = array(
    4, 0, 2, 0, 3
);

uasort($arr, function($a, $b){
    if ($a == 0) {
        return 1;
    }
    if ($b == 0) {
        return -1;
    }
    return ($a < $b) ? -1 : 1;
});

print_r($arr);
gmsantos
  • 1,332
  • 19
  • 28
Piotr Olaszewski
  • 5,521
  • 5
  • 34
  • 58
1

Using a custom sort function you could use:

function usortTest($a, $b) {

    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;

    return gmp_cmp($a, $b);

}

$test = array(4,0,2,0,3);
usort($test, "usortTest");

print_r($test);

May need to be refactored/improved, but the documentation should help you understand custom sort functions.

Tom Walters
  • 13,978
  • 5
  • 53
  • 71
  • 1
    [usort](http://php.net/manual/en/function.usort.php) doesn't not preserve index association, should use [uasort](http://php.net/manual/en/function.uasort.php) function. – Piotr Olaszewski Jan 23 '15 at 10:47
1

There is a PHP function call uasort that lets you define a function to sort an array and maintain array key ordering.

The return value of your defined function must be 0, -1 or 1 depending on if the values are the same, if the second value is less than the first value, or if the second value is greater than the first value, respectively.

To achieve what you are attempting would require a function similar to:

$array = array(4,0,2,0,3);
uasort($array, function($a,$b) {
    // push all 0's to the bottom of the array
    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;   
    if($a == $b) {return 0; }   // values are the same
    return ($a < $b) ? -1 : 1;  // smaller numbers at top of list
});
var_dump($array);
/*
array (size=5)
  2 => int 2
  4 => int 3
  0 => int 4
  3 => int 0
  1 => int 0
*/
Richard Parnaby-King
  • 13,858
  • 11
  • 64
  • 123
0

Or go with what @axiac said:

$a = array(4, 0, 2, 0, 3);

function getZeros(&$a) {
    $zeros = array();
    for($i = 0; $i < count($a); $i++) {
        if($a[$i] === 0) {
            $zeros[] = 0;
            unset($a[$i]);
        }
    }

    return $zeros;
}

$zeros = getZeros($a);
sort($a);
$a = array_merge($a, $zeros);

echo join(', ', $a);
Sergiu Paraschiv
  • 9,575
  • 5
  • 33
  • 45