English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The PHP array_splice() function removes a part of an array and replaces it with other values
array_splice ( $input, $offset [,$length [,$replacement]] );
This function frominputelements fromoffsetandlengthspecified elements, andreplacementArray elements (if provided) replace them. It returns an array containing the extracted elements.
Note that the numeric keys in input are not retained.
Number | Parameters and descriptions |
---|---|
1 | input(required) It specifies an array |
2 | offset It specifies where the function will start deleting elements. 0=first element. |
3 | length(optional) It specifies the number of elements to delete and the length of the returned array. |
4 | replacement(optional) It specifies an array that contains the elements to be inserted into the original array. |
Returns an array containing the removed elements.
Using array_splice to modify an array
<?php $input = array("red", "black", "pink", "white"); array_splice($input, 2); print_r($input); print_r("<br />) $input = array("red", "black", "pink", "white"); array_splice($input, 1, -1); print_r($input); print_r("<br />) $input = array("red", "black", "pink", "white"); array_splice($input, 1, count($input), "orange"); print_r($input); print_r("<br />) $input = array("red", "black", "pink", "white"); array_splice($input, -1, 1, array("black", "maroon")); print_r($input); print_r("<br />) $input = array("red", "black", "pink", "white"); array_splice($input, 3, 0, "purple"); print_r($input); print_r("<br />) ?>Test and see‹/›
Output result:
Array ( [0]=>red [1] =>black ) Array ( [0]=>red [1] =>white ) Array ( [0]=>red [1] =>orange ) Array ( [0]=>red [1] =>black [2pink [3] =>black [4maroon ) Array ( [0]=>red [1] =>black [2pink [3purple [4white )