Inside Rejoan Inside Rejoan - 7 months ago 30
PHP Question

php array push element at an index and move the previous element

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?

Answer

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"
}
Comments