The array_splice()
function removes the selected element from the array and replaces it with a new element. This function will also return an array containing the removed elements.
Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the start parameter position (see Example 2).
Note: The key names in the replaced array are not retained.
Remove the element from the array and replace it with a new element:
<?php $a1 = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ) ; $a2 = array ( "a" => "purple" , "b" => "orange" ) ; array_splice ( $a1 , 0 , 2 , $a2 ) ; print_r ( $a1 ) ; ?>
Try it yourself
Same as the example in the previous section of this page, but output the returned array:
<?php $a1 = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ) ; $a2 = array ( "a" => "purple" , "b" => "orange" ) ; print_r ( array_splice ( $a1 , 0 , 2 , $a2 ) ) ; ?>
Try it yourself
Set length parameter to 0:
<?php $a1 = array ( "0" => "red" , "1" => "green" ) ; $a2 = array ( "0" => "purple" , "1" => "orange" ) ; array_splice ( $a1 , 1 , 0 , $a2 ) ; print_r ( $a1 ) ; ?>
Try it yourself
array_splice ( array , start , length , array )
parameter | describe |
---|---|
array | Required. Specify array. |
start |
Required. Value. Specifies the starting position of the delete element.
|
length |
Optional. Value. Specifies the number of elements removed, and is also the length of the returned array.
|
array |
Optional. Specifies an array with elements to be inserted into the original array. If there is only one element, it can be set to a string, and does not need to be set to an array. |
The array_splice()
function is similar to array_slice()
function, selecting a series of elements in an array, but not returning, but deleting them and replacing them with other values.
If the fourth parameter is provided, those previously selected elements will be replaced by the array specified by the fourth parameter.
The last generated array will be returned.