How is the array_splice function used in PHP?
The array_splice() function is used to insert or remove elements in an array and returns the elements that were removed. Its syntax is as follows:
Modify an array by removing a portion and optionally replacing it with new elements.
Explanation of parameters:
- $input: Required, the original array.
- $offset: Required, specifies the starting position for insertion/removal. If it is a negative number, it starts from the end.
- $length: Optional, specifies the number of elements to be deleted. Default is 0, indicating no elements will be deleted.
- $replacement: Optional. Specifies the element to be inserted. If not specified, the element at the specified position is removed.
Return value: An array containing the deleted elements is returned.
Example 1: Remove elements from the array
$arr = ['apple', 'banana', 'orange', 'grape'];
$removed = array_splice($arr, 1, 2);
print_r($arr); // 输出:['apple', 'grape']
print_r($removed); // 输出:['banana', 'orange']
Inserting elements into an array.
$arr = ['apple', 'grape'];
array_splice($arr, 1, 0, 'banana', 'orange');
print_r($arr); // 输出:['apple', 'banana', 'orange', 'grape']
Please note that the array_splice() function will modify the original array.