Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move an array element to a new index in PHP

Tags:

arrays

php

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' ] 
like image 884
cronoklee Avatar asked Sep 27 '12 14:09

cronoklee


People also ask

How do I change the index of an array element in PHP?

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.

How do you change an element from an array to an index?

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.

How do I push an item into 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.


1 Answers

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', ]; 
like image 139
hakre Avatar answered Sep 30 '22 18:09

hakre