PHP array_splice()
Function
Complete PHP Array Reference Manual
Example
Remove elements from an array and replace 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);
?>
Definition and Usage
The array_splice()
function removes the selected elements from an array and replaces them with new elements. The function also returns the array of removed elements.
Tip: If no elements are removed (length=0), the replacement array will be inserted at the position specified by the start parameter (see Example 2).
Note: The keys in the replacement array are not preserved.
Syntax
Parameter | Description |
---|---|
array1 | Required. Specifies the array. |
start | Required. Numeric. Specifies the starting position for removing elements. |
0 = the first element. If this value is set to a positive number, elements are removed starting from the specified offset. If this value is set to a negative number, elements are removed starting from the end of the array, counting back from the specified offset. -2 means starting from the second to last element. <br> | | length | Optional. Numeric. Specifies the number of elements to remove, and also the length of the returned array. If this value is set to a positive number, that many elements are removed. If this value is set to a negative number, elements are removed from the start to the end of the array, stopping length elements from the end. If this value is not set, all elements from the start position to the end of the array are removed. <br> | | array2 | Optional. Specifies the array of elements to insert into the original array. If it contains only one element, it can be set as a string, not necessarily as an array. |
Technical Details
Return Value: | Returns an array containing the removed elements. |
---|---|
PHP Version: | 4+ |
--- | --- |
More Examples
Example 1
Same as the example earlier on this page, but outputting 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));
?>
Example 2
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);
?>