phparrayssortingassociative-arraypreserve

Move an element to a new position in an associative array (preserving all keys)


I want to move array element with key to other position of array.

My actual Array

  Array
    (
        [24] => Birthday
        [25] => Christmas
        [26] => Congratulations
        [27] => Halloween
        [28] => Mothers Day
    )

I want to move [25] => Christmas element like below.

Array
    (
        [24] => Birthday  
        [26] => Congratulations
        [27] => Halloween
        [25] => Christmas
        [28] => Mothers Day         
    )

Solution

  • Live on ide1: http://ideone.com/yJ1e3N

    Use uasort to keep key-value association while ordering with a custom logic using a closure:

    $order = [
       'Birthday' => 1,
       'Congratulations' => 2,
       'Halloween' => 3,
       'Christmas' => 4,
       'Mothers Day' => 5 
    ];
    
    uasort($array, function($a,$b) use ($order){
      return $order[$a] > $order[$b];
    });
    

    With this script you can use any custom order logic you need by assigning the right value to the array $order. This will be also very fast if you have many elements as the right order is accessed using the keys of the $order array (and not by a linear scan).