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?

10
  • @Praveen Kumar please read first. I have different requirement Commented Apr 22, 2016 at 10:48
  • I checked it fully and perfectly. It works. Commented Apr 22, 2016 at 10:49
  • You have 'a', 'b', 'c', 'd', 'e' and you wanna put in 'x', and you get this: a b c x d e right? Commented Apr 22, 2016 at 10:49
  • Try it out, and if it didn't work, I am happy to reopen the question. Commented Apr 22, 2016 at 10:50
  • Oh okay... I just had a better view. You can do it using pop(). Lemme reopen. Sorry for that. Commented Apr 22, 2016 at 10:52

2 Answers 2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.