Wiram Rathod
Wiram Rathod

Reputation: 1919

Php array move element to other postion with key value pair

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         
    )

Upvotes: 2

Views: 186

Answers (2)

ProudEngineers
ProudEngineers

Reputation: 54

If you are getting the data from table, you can add another column as order_column and specify the order in that column. Then modify your select query such that you ORDER BY order_column.

Upvotes: 0

dynamic
dynamic

Reputation: 48091

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

Upvotes: 2

Related Questions