Remove elements from an array and substitute them with new elements.
<?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); ?> |
The array_splice() function removes specified elements from an array and replaces them with new elements. It also returns an array containing the removed elements.
Tip: If no elements are removed (length=0), the new elements are inserted at the position specified by the start parameter (see Example 2).
Note: The keys in the replaced array are not preserved.
array_splice(array, start, length, array) |
Parameter |
Description |
array |
Required. Specifies the array to modify. |
start |
Required. Numeric value. Specifies the position where the function will begin removing elements. 0 refers to the first element. If set to a negative number, the function will start that many positions from the end of the array. For example, -2 means start at the second-to-last element. |
length |
Optional. Numeric value. Specifies how many elements will be removed and determines the length of the returned array. If set to a negative number, the function will stop removing elements that many positions from the end of the array. If this value is not provided, the function will remove all elements starting from the position specified by the start parameter. |
array |
Optional. Specifies an array of elements to insert into the original array. If only one element is being inserted, it can be a string instead of an array. |
Return Value: |
Returns an array containing the removed elements. |
PHP Version: |
4+ |
The same example as shown earlier on the page, but with the output being 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)); ?> |
With the length parameter set to 0:
<?php $a1=array(“0”=>“red”,“1”=>“green”); $a2=array(“0”=>“purple”,“1”=>“orange”); array_splice($a1,1,0,$a2); print_r($a1); ?> |