0

This is my array. I want to push an element at index 3 and at the same time move the previous element to next. Please read first its not array_splice() work

array(6) {
  [0]=>
  string(1) "One_test"
  [1]=>
  string(1) "Two_test"
  [2]=>
  string(1) "Three_test"
  [3]=>
  string(1) "Four_test"
  [4]=>
  string(1) "Five_test"
  [5]=>
  string(1) "Six_test"
}

So my desired output is

array(6) {
  [0]=>
  string(1) "One_test"
  [1]=>
  string(1) "Two_test"
  [2]=>
  string(1) "Three_test"
  [3]=>
  string(1) "Six_test"
  [4]=>
  string(1) "Four_test"
  [5]=>
  string(1) "Five_test"
}

So notice I need replace 3rd indexed element with 5th indexed element and then move previously 3rd indexed element into next. Finally the pushed element (5th) to remove

Any Idea?

Rejoanul Alam
  • 5,047
  • 3
  • 31
  • 62

2 Answers2

2

Inspired from the dupe: Insert new item in array on any position in PHP

I would do a array_pop() and array_slice()on the array:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$new_one = array_pop($original);

array_splice( $original, 3, 0, $new_one );

My Solution

So before:

array(6) {
  [0]=>
  string(8) "One_test"
  [1]=>
  string(8) "Two_test"
  [2]=>
  string(10) "Three_test"
  [3]=>
  string(9) "Four_test"
  [4]=>
  string(9) "Five_test"
  [5]=>
  string(8) "Six_test"
}

And After:

array(6) {
  [0]=>
  string(8) "One_test"
  [1]=>
  string(8) "Two_test"
  [2]=>
  string(10) "Three_test"
  [3]=>
  string(8) "Six_test"
  [4]=>
  string(9) "Four_test"
  [5]=>
  string(9) "Five_test"
}
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
0

This method takes your array, the index of the item you want to move, and the index at which you want to push the item to.

function moveArrayItem($array, $currentPosition, $newPosition){

    //get value of index you want to move
    $val = array($array[$currentPosition]);

    //remove item from array
    $array = array_diff($array, $val);

    //push item into new position
    array_splice($array,$newPosition,0,$val);

    return $array;
}

Example of use:

$a = array("first", "second", "third", "fourth", "fifth", "sixth");

$newArray = moveArrayItem($a, 5, 3);