I have an array of elements like this:
$data = array(1, 2, 3, 4);
How can I reorder for example, starting from second element to get 2, 3, 4, 1
; or starting from third element to get 3, 4, 1, 2
?
I have an array of elements like this:
$data = array(1, 2, 3, 4);
How can I reorder for example, starting from second element to get 2, 3, 4, 1
; or starting from third element to get 3, 4, 1, 2
?
One solution is to use array_slice
function to separate the two portions and combine them with array_merge
:
$data = [1, 2, 3, 4];
$pos = 2;
$ordered = array_merge(
array_slice($data, $pos),
array_slice($data, 0, $pos)
);
// [3, 4, 1, 2]
You can use array_splice
$data = array(1,2,3,4);
$out = array_splice($data, 1, 3);
array_splice($data, 0, 0, $out);
print_r($data);
You could just array_shift()
and then push the shifted value back on to the end of the Array:
$data = array(1,2,3,4);
$data[] = array_shift($data);