March 16, 2011

How do I remove an element from an array and insert into another position in PHP?

Question by deltanovember

For example suppose I have

$input = array(0, 1, 2, 3, 4, 5, 6, 7);

How would I remove element 5 and insert at position 2 leaving me with

0, 1, 5, 2, 3, 4, 6, 7

Answer by Starx

$input = array(0, 1, 2, 3, 4, 5, 6, 7);
array_splice($input, 2, 0, array($input[5])); //Place the a new array in the 3rd place of array
unset($input[6]); //remove the fifth element
array_splice($input, 0, 0); //to update the indexes

echo "<pre>".print_r($input,1)."</pre>"; //to view the array

Method without the need to unset and rearrange the index

$input = array(0, 1, 2, 3, 4, 5, 6, 7);
array_splice($input, 2, 0, array_splice($input,5,1)); 

Output

Array
(
    [0] => 0
    [1] => 1
    [2] => 5
    [3] => 2
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
)

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!