Reputation: 5471
I'm trying to move the last three elements of an array, to become the first three elements. Is this possible? The array is variable depending on what page you're on, but it will look something like this:
Array
(
[4] => 1
[2] => 2
[3] => 6
[5] => 9
[0] => 10
[1] => 11
)
and I need it to be:
Array
(
[5] => 9
[0] => 10
[1] => 11
[4] => 1
[2] => 2
[3] => 6
)
Any help would be appreciated. The length of the array will also differ per page, so I'm not 100% sure how to go about it.
Upvotes: 0
Views: 52
Reputation: 781761
array_splice()
is used to extract and insert sequences of elements in an array.
array_splice($array, 0, 0, array_splice($array, -3));
array_splice($array, -3)
removes the last 3 elements of the array and returns that as an array. Then array_splice($array, 0, 0, <that>)
inserts that array at the beginning of the array.
Note that this doesn't preserve keys of associative arrays, which seems to be necessary in your example. For that, you can use the array_rotate
function defined in the documentation notes
function array_rotate($array, $shift) {
if(!is_array($array) || !is_numeric($shift)) {
if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
return $array;
}
$shift %= count($array); //we won't try to shift more than one array length
if($shift < 0) $shift += count($array);//handle negative shifts as positive
return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
Upvotes: 1
Reputation: 658
Note that array_splice
doesnt preserve numeric keys (as seems to be the case according to the OP example). If you need that, this will work too:
$array1 = array
(
4 => 1,
2 => 2,
3 => 6,
5 => 9,
0 => 10,
1 => 11
);
$array2 = array_slice($array1, -3, 3, true) + $array1;
And $array2 will be:
Array
(
[5] => 9
[0] => 10
[1] => 11
[4] => 1
[2] => 2
[3] => 6
)
Upvotes: 2