Secret
Secret

Reputation: 3358

Swap my element's order to be the first in an array

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)

Upvotes: 1

Views: 95

Answers (3)

scrowler
scrowler

Reputation: 24405

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

Upvotes: 1

Mark Miller
Mark Miller

Reputation: 7447

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

Upvotes: 2

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21671

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.

Upvotes: -2

Related Questions