Search code examples
phparrayssortingkeycustom-sort

Move all odd-keyed elements to the back of the array


I have an array with numeric keys and I need to move all elements with odd keys to the end of the array.

[
    0 => 'apples',
    1 => 'oranges',
    2 => 'peaches',
    3 => 'pears',
    4 => 'watermelon'
]

What I am looking to do is something like this

[
    0 => 'apples',
    2 => 'peaches',
    4 => 'watermelon',
    1 => 'oranges',
    3 => 'pears'
]

It does not matter if the array keys change or not, I just need the location of the values to change.


Solution

  • <?php
    $fruit = array('apples', 'oranges', 'peaches', 'pears', 'watermelon');
    
    function fruitCmp($a, $b) {
        if ($a == $b) {
            return 0;
        }
    
        $aIsOdd = $a % 2;
        $bIsOdd = $b % 2;
    
        if (($aIsOdd && $bIsOdd) || (!$aIsOdd && !$bIsOdd)) {
            return $a < $b ? -1 : 1;
        }
    
        if ($aIsOdd && !$bIsOdd) {
            return 1;
        }
    
        if (!$aIsOdd && $bIsOdd) {
            return -1;
        }
    }
    
    uksort($fruit, 'fruitCmp');
    
    var_dump($fruit);
    

    Output:

    array(5) {
      [0]=>
      string(6) "apples"
      [2]=>
      string(7) "peaches"
      [4]=>
      string(10) "watermelon"
      [1]=>
      string(7) "oranges"
      [3]=>
      string(5) "pears"
    }