PHP array_splice() function
Example
Remove elements from the 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 selected elements from the array and replaces them with new elements. This function also returns an array containing the removed elements.
Tip:If the function does not remove any elements (length=0), then from start Insert the replaced array at the position of the parameters (see example 2).
Note:The keys in the replaced array are not retained.
Description
The array_splice() function is similar to array_slice() The function is similar, selecting a series of elements from the array, but it does not return them, instead, it deletes them and replaces them with other values.
If the fourth parameter is provided, the previously selected elements will be replaced by the array specified by the fourth parameter.
The resulting array will be returned.
Syntax
array_splice(array,start,length,array)
Parameters | Description |
---|---|
array | Required. Specifies the array. |
start |
Required. Numeric. Specifies the starting position of the element to be deleted.
|
length |
Optional. Numeric. Specifies the number of elements to be removed, which is also the length of the returned array.
|
array |
Optional. Specifies an array that contains the elements to be inserted into the original array. If only one element is present, it can be set as a string without being set as an array. |
Technical Details
Return Value: | Returns an array composed of the extracted elements. |
PHP Version: | 4+ |
More Examples
Example 1
Similar to the example in the previous part 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)); ?>
Example 2
Set the 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); ?>