PHP array_splice() Function
Complete PHP Array Reference Manual
Example
Remove elements from an array and replace them with new ones:
" red " , " b " => " green " , " c " => " blue " , " d " => " yellow " ) ; $a2 = array ( " a " => " purple " , " b " => " orange " ) ; array_splice ( $a1 , 0 , 2 , $a2 ) ; print_r ( $a1 ) ; ?>Run Example »
Definition and Usage
The array_splice() function removes selected elements from an array and replaces them with new elements. It also returns an array of the removed elements.
**Tip:** If the function removes no elements (length=0), the replacement array is inserted at the position given by the start parameter (see Example 2).
**Note:** The keys in the replacement array are not preserved.
Syntax
array_splice(
array1,start,length,array2
)
| Parameters | Description |
|---|---|
| array1 | Required. Specifies the array. |
| start | Required. Numeric. Specifies where to start removing elements. 0 = the first element. If this value is positive, removal starts at that offset from the beginning of the array. If it is negative, removal starts at that offset from the end of the array. -2 means start at the second-to-last element. |
| length | Optional. Numeric. Specifies the number of elements to remove and the length of the returned array. If this value is positive, that many elements are removed. If it is negative, all elements from start up to the point that far from the end of the array are removed. If not set, all elements from the position set by the start parameter to the end of the array are removed. |
| array2 | Optional. Specifies an array with elements to insert into the original array. If there is only one element, it can be set to a string rather than an array. |
Technical Details
| Return Value: | Returns an array containing the extracted elements. |
|---|---|
| PHP Version: | 4+ |
More examples
Example 1
Same as the example earlier on this page, but outputs the returned array:
" red " , " b " => " green " , " c " => " blue " , " d " => " yellow " ) ; $a2 = array ( " a " => " purple " , " b " => " orange " ) ; print_r ( array_splice ( $a1 , 0 , 2 , $a2 ) ) ; ?>Run Example »
Example 2
With the length parameter set to 0:
" red " , " 1 " => " green " ) ; $a2 = array ( " 0 " => " purple " , " 1 " => " orange " ) ; array_splice ( $a1 , 1 , 0 , $a2 ) ; print_r ( $a1 ) ; ?>Run Example »
Complete PHP Array Reference Manual