array_splice()
Think of this function as substr_replace() for arrays. You say where to start and how many elements to remove (or don’t and get all to the end) and supply a second array with the elements you want to put into that spot.
Negative values for offset and length are as they would be in substr() - they count from the end.
It’s important to note that your initial array is being changed. What this function returns is the section that was removed. Also, any numeric keys of your original array will be re-indexed and all keys of the array you’re inserting will be re-indexed numerically.
$arr1 = array( 2 => 'apple', 'banana', 'carrot', 'd' => 'durian', 'eggplant', 'fennel', 'g' => 'grapefruit', 'honeydew', 'iceburg lettuce', 'jackfruit', 'kale' ); $arr2 = array( 'Greg', 'Peter', 'Bobby', 'AnnBDavis' => 'Alice', 'Marsha', 'Jan', 'Cindy' ); $copy = $arr1; array_splice( $copy, 5 ); /* array ( 0 => 'apple', 1 => 'banana', 2 => 'carrot', 'd' => 'durian', 3 => 'eggplant' ) */ $copy = $arr1; array_splice( $copy, 5, 2 ); /* array ( 0 => 'apple', 1 => 'banana', 2 => 'carrot', 'd' => 'durian', 3 => 'eggplant', 4 => 'honeydew', 5 => 'iceburg lettuce', 6 => 'jackfruit', 7 => 'kale' ) */ $copy = $arr1; array_splice( $copy, 5, -2 ); /* array ( 0 => 'apple', 1 => 'banana', 2 => 'carrot', 'd' => 'durian', 3 => 'eggplant', 4 => 'jackfruit', 5 => 'kale' ) */ $copy = $arr1; array_splice( $copy, 5, 2, $arr2 ); /* array ( 0 => 'apple', 1 => 'banana', 2 => 'carrot', 'd' => 'durian', 3 => 'eggplant', 4 => 'Greg', 5 => 'Peter', 6 => 'Bobby', 7 => 'Alice', 8 => 'Marsha', 9 => 'Jan', 10 => 'Cindy', 11 => 'honeydew', 12 => 'iceburg lettuce', 13 => 'jackfruit', 14 => 'kale' ) */ $copy = $arr1; array_splice( $copy, 5, 0, $arr2 ); /* array ( 0 => 'apple', 1 => 'banana', 2 => 'carrot', 'd' => 'durian', 3 => 'eggplant', 4 => 'Greg', 5 => 'Peter', 6 => 'Bobby', 7 => 'Alice', 8 => 'Marsha', 9 => 'Jan', 10 => 'Cindy', 11 => 'fennel', 'g' => 'grapefruit', 12 => 'honeydew', 13 => 'iceburg lettuce', 14 => 'jackfruit', 15 => 'kale' ) */
See the manual entry for array_splice()
