PHP array_splice() Function
PHP array_splice() Function
The array_splice() function in PHP is used to remove a portion of the array and replaces them with the elements of the replacement array.
Syntax
array_splice (array &$input, int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )
Parameter
input(required)- This array represents the input array.
offset(required)-This parameter signifies the starting position of the array from where the splicing needs to be performed. The various offset values are as follows:
- If it is greater than 0, the start of the removed portion is at that offset from the beginning of the input array.
- If offset is negative, the start of the removed portion is at that offset from the end of the input array.
length(optional)- This parameter refers to the range or limit point upto which the splicing is needed to be done.
- If length is not specified, it removes everything from offset to the end of the array.
- If length is positive, the specified number of elements will be removed.
- If length is negative, the end of the removed portion will be that many elements from the end of the array.
- If length is equal to zero, no elements will be removed.
replacement (optional)- This parameter represents the replacement array wherein the removed elements are replaced with elements from this array.
Return
This function returns an array consisting of the extracted elements.
Example 1
Output
Input Array: Array ( [0] => a [1] => b [2] => c [3] => d [4] => e ) Sliced Array: Array ( [0] => c [1] => d [2] => e )Example 2
Output
New Array: Array ( [0] => d )Example 3
Output
Input Array: Array ( [0] => apple [1] => banana [2] => carrot [3] => lemons [4] => dates ) New Array: Array ( [0] => dates )Example 4
Output
Input Array: Array ( [0] => apple [1] => banana [2] => carrot [3] => lemons [4] => dates ) New Array: Array ( [0] => banana [1] => carrot [2] => lemons [3] => dates )