I\'m looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt ne
A function that preserves keys:
function moveElementInArray($array, $toMove, $targetIndex) {
if (is_int($toMove)) {
$tmp = array_splice($array, $toMove, 1);
array_splice($array, $targetIndex, 0, $tmp);
$output = $array;
}
elseif (is_string($toMove)) {
$indexToMove = array_search($toMove, array_keys($array));
$itemToMove = $array[$toMove];
array_splice($array, $indexToMove, 1);
$i = 0;
$output = Array();
foreach($array as $key => $item) {
if ($i == $targetIndex) {
$output[$toMove] = $itemToMove;
}
$output[$key] = $item;
$i++;
}
}
return $output;
}
$arr1 = Array('a', 'b', 'c', 'd', 'e');
$arr2 = Array('A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e');
print_r(moveElementInArray($arr1, 3, 1));
print_r(moveElementInArray($arr2, 'D', 1));
Ouput:
Array
(
[0] => a
[1] => d
[2] => b
[3] => c
[4] => e
)
Array
(
[A] => a
[D] => d
[B] => b
[C] => c
[E] => e
)