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 need to work with associative arrays. Anyone got ideas for this one?
$a = array( 0 => 'a', 1 => 'c', 2 => 'd', 3 => 'b', 4 => 'e', ); print_r(moveElement(3,1)) //should output [ 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e' ]
We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.
To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.
In order to insert an element in the specific index, we need to provide the arguments as: start → the index in which to insert the element. deleteCount → 0 (because we don't need to delete any elements). elem → elements to insert.
As commented, 2x array_splice
, there even is no need to renumber:
$array = [ 0 => 'a', 1 => 'c', 2 => 'd', 3 => 'b', 4 => 'e', ]; function moveElement(&$array, $a, $b) { $out = array_splice($array, $a, 1); array_splice($array, $b, 0, $out); } moveElement($array, 3, 1);
Result:
[ 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With