Search code examples
phparrayssortingcustom-sort

Custom sort a flat array of scalar values ​so that integers are given top priority


I have an array like this:

$arr = [456, 8, 1, -9, 'string', true, 0, -65, -162];

I want to sort array values descending and also I want integer values to be above the other value types,

I've tried with rsort($arr) , then I do var_dump, but the result is

array (size=9)
0 => int 456
1 => int 8
2 => int 1
3 => string 'string' (length=6)
4 => int -9
5 => boolean true
6 => int 0
7 => int -65
8 => int -162

How do make that array sorted with integer above the other data type?

Desired result:

$arr = [456, 8, 1, 0, -9,-65, -162, 'string', true]

Solution

  • You can use usort with a custom sort function which checks for integers before comparing values:

    usort($arr, function ($a, $b) {
        if (is_integer($a) && !is_integer($b)) return -1;
        elseif (!is_integer($a) && is_integer($b)) return 1;
        else return $b <=> $a;
    });
    var_dump($arr);
    

    Output:

    array(9) {
      [0]=>
      int(456)
      [1]=>
      int(8)
      [2]=>
      int(1)
      [3]=>
      int(0)
      [4]=>
      int(-9)
      [5]=>
      int(-65)
      [6]=>
      int(-162)
      [7]=>
      string(6) "string"
      [8]=>
      bool(true)
    }
    

    Demo on 3v4l.org