phparrayssortingassociative-arraypreserve

Move a key-value pair to a new position in an associative array while preserving all keys


I have an array like this:

array (size=8)
  'cb' => string '<input type="checkbox"/>' (length=24)
  'title' => string 'Name' (length=4)
  'download_category' => string 'Categories' (length=10)
  'download_tag' => string 'Tags' (length=4)
  'price' => string 'Price' (length=5)
  'sales' => string 'Sales' (length=5)
  **'earnings' => string 'Earnings' (length=8)**
  'shortcode' => string 'Purchase Short Code' (length=19)
  'date' => string 'Date' (length=4)

Now what I want to do, is move the 'earnings' one, to the third position like this:

array (size=9)
  'cb' => string '<input type="checkbox"/>' (length=24)
  'title' => string 'Name' (length=4)
  **'earnings' => string 'Earnings' (length=8)**
  'download_category' => string 'Categories' (length=10)
  'download_tag' => string 'Tags' (length=4)
  'price' => string 'Price' (length=5)
  'sales' => string 'Sales' (length=5)
  'shortcode' => string 'Purchase Short Code' (length=19)
  'date' => string 'Date' (length=4)

The first 9 elements of this array are static in the sense that the order is fixed, but there may be more elements to this array (after 'date') if that matters.

Therefore, I'm looking for an easy way to move the xth element in front of the current 3rd element's position.

One thing I have tried is saving the first 2 elements to a variable, then unsetting them. I also unset the earnings element to a variable. So the array then begins with the 3rd element. Then, since I want my element ahead of the 3rd element, and I need those other 2 elements back in, like this:

$first = $array[0];
$second = $array[1];
$earnings_element = $array['earnings'];
unset($array[0]); 
unset($array[1]);
unset($array['earnings']);
array_unshift($array,$first,$second,$earnings_element);

The problem is that either I lose the element name (it becomes a key value of 1,2,etc) or the value of that elements inserted back in the unshift.

Anyone know of an easier method?

Edit: I am using "array" as the name for the array in the code below. Its not the name of the actual array.


Solution

  • Try this:

    $front = array_slice($array,0,2);
    $front['earnings'] = $array['earnings'];
    $back = array_slice($array,2);
    unset($back['earnings']);
    $array = array_merge($front,$back);