php - Swap my element's order to be the first in an array -
let's have array so:
array( [0]=>1 [1]=>3 [3]=>5 [15]=>6 );
arbitrarily want array[15] first:
array( [15]=>6 [0]=>1 [1]=>3 [3]=>5 );
what fastest , painless way this?
here things i've tried:
array_unshift
- unfortunately, keys numeric , need keep order (sort of uasort
) messes keys.
uasort
- seems overhead - reason want make element first in array avoid uasort
! (swapping elements on fly instead of sorting when need them)
you can try this using slice , union operator:
// last element (preserving keys) $last = array_slice($array, -1, 1, true); // put union operator $array = $last + $array;
update: as mentioned below, answer takes last key , puts @ front. if want arbitrarily move element front:
$array = array($your_desired_key => $array[$your_desired_key]) + $array;
union operators take right , add left (so original value gets overwritten).
Comments
Post a Comment