Array_splice definition and usage
The array_splice () function is similar to the array_slice () function. It selects a series of elements in the array but does not return them. Instead, it deletes them and replaces them with other values.
If the fourth parameter is provided, the selected elements are replaced by the array specified by the fourth parameter.
The final generated array will be returned.
Syntax
Array_splice (array, offset, length, array) parameter description
Array is required. Specified array.
Offset is required. Value. If the offset value is positive, it is removed from the offset specified by this value in the input array. If offset is negative, it is removed from the offset specified by the reciprocal value at the end of the input array.
Length is optional. Value. If this parameter is omitted, all parts from the offset to the end of the array are removed. If length is specified and it is a positive value, so many elements are removed. If length is specified and it is a negative value, all the elements from the offset to the reciprocal length at the end of the array are removed.
The elements removed from the array are replaced by the elements in the array. If no value is removed, the elements in this array are inserted to the specified position.
Tips and comments
Tip: If the function does not delete any element (length = 0), the replacement array is inserted from the start parameter. (See example 3)
Note: Do not retain the replacement keys in the array.
Example 1
Copy codeThe Code is as follows:
<? Php
$ A1 = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
$ A2 = array (0 => "Tiger", 1 => "Lion ");
Array_splice ($ a1, 0, 2, $ a2 );
Print_r ($ a1 );
?>
Output:
Array ([0] => Tiger [1] => Lion [2] => Horse [3] => Bird) Example 2
Same as Example 1, but the returned array is output:
Copy codeThe Code is as follows:
<? Php
$ A1 = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
$ A2 = array (0 => "Tiger", 1 => "Lion ");
Print_r (array_splice ($ a1, 0, 2, $ a2 ));
?>
Output:
Array ([0] => Dog [1] => Cat) Example 3
The length parameter is set to 0:
Copy codeThe Code is as follows:
<? Php
$ A1 = array (0 => "Dog", 1 => "Cat ");
$ A2 = array (0 => "Tiger", 1 => "Lion ");
Array_splice ($ a1, 1, 0, $ a2 );
Print_r ($ a1 );
?>
Output:
Array ([0] => Dog [1] => Tiger [2] => Lion [3] => Cat)