1

Let's say I have an array like so:

array(
  [0]=>1
  [1]=>3
  [3]=>5
  [15]=>6
);

Arbitrarily I want array[15] to be the first:

array(
  [15]=>6
  [0]=>1
  [1]=>3
  [3]=>5
);

What is the fastest and most painless way to do this?

Here are the things I've tried:

array_unshift - Unfortunately, my keys are numeric and I need to keep the order (sort of like uasort) this messes up the keys.

uasort - seems too much overhead - the reason I want to make my element the first in my array is to specifically avoid uasort! (Swapping elements on the fly instead of sorting when I need them)

Secret
  • 3,224
  • 3
  • 31
  • 47

3 Answers3

2

Assuming you know the key of the element you want to shift, and that element could be in any position in the array (not necessarily the last element):

$shift_key = 15;

$shift = array($shift_key => $arr[$shift_key]);

$arr = $shift + $arr;

See demo

Updated - unset() not necessary. Pointed out by @FuzzyTree

Mark Miller
  • 7,442
  • 2
  • 15
  • 21
  • 2
    `unset` isn't necessary because the union operator will use the value from the left array when keys exist in both arrays – FuzzyTree Jun 26 '14 at 03:49
1

You can try this using a slice and a union operator:

// get last element (preserving keys)
$last = array_slice($array, -1, 1, true);

// put it back with union operator
$array = $last + $array;

Update: as mentioned below, this answer takes the last key and puts it at the front. If you want to arbitrarily move any element to the front:

$array = array($your_desired_key => $array[$your_desired_key]) + $array;

Union operators take from the right and add to the left (so the original value gets overwritten).

Community
  • 1
  • 1
scrowler
  • 23,965
  • 9
  • 60
  • 90
-2

If #15 is always last you can do

$last = array_pop($array); //remove from end
array_unshift($last); //push on front

To reorder the keys for sorting simply add

$array = array_values($array); //reindex array

@Edit - if we don't assume its always last then I would go with ( if we always know wwhat the key is, then most likely we will know its position or it's not a numerically indexed array but an associative one with numeric keys, as op did state "arbitrarily" so one has to assume the structure of the array is known before hand. )

I also dont see the need to reindex them as the op stated that it was to avoid sorting. So why would you then sort?

$item = $array[15];
unset($array[15]); //....etc.
ArtisticPhoenix
  • 20,856
  • 2
  • 21
  • 35