This function will allow you to move an element to an arbitrary position within the array, while leaving the rest of the array untouched:
function array_reorder($array, $oldIndex, $newIndex) {
array_splice(
$array,
$newIndex,
count($array),
array_merge(
array_splice($array, $oldIndex, 1),
array_slice($array, $newIndex, count($array))
)
);
return $array;
}
Hopefully the usage is fairly obvious, so this:
$array = array('red','green','blue','yellow',);
var_dump(
array_reorder($array, 3, 0),
array_reorder($array, 0, 3),
array_reorder($array, 1, 3),
array_reorder($array, 2, 0)
);
Will output this:
array(4) {
[0]=>
string(6) "yellow"
[1]=>
string(3) "red"
[2]=>
string(5) "green"
[3]=>
string(4) "blue"
}
array(4) {
[0]=>
string(5) "green"
[1]=>
string(4) "blue"
[2]=>
string(6) "yellow"
[3]=>
string(3) "red"
}
array(4) {
[0]=>
string(3) "red"
[1]=>
string(4) "blue"
[2]=>
string(6) "yellow"
[3]=>
string(5) "green"
}
array(4) {
[0]=>
string(4) "blue"
[1]=>
string(3) "red"
[2]=>
string(5) "green"
[3]=>
string(6) "yellow"
}
yellow, red, green, blue,yellow, blue, green, red,yellow, green, blue, redand each of these would have different processes. Furthermore does it always have to be the end to the front or is it an arbitrary position to the front?yellowwithred, okay it is a clearer duplicate page with an full minimal reproducible example. If this question is about movingyellowto a new position and affecting all other elements in its path to the new position, then it is not a suitable duplicate. This question is too ambiguous -- this is why I've voted as Unclear.