PHP array_splice function
Last Updated: February 15, 2022
array_splice — Remove the portion of the array or replace portion of the array
Syntax
array_splice(
array &$array,
int $offset,
?int $length = null,
mixed $replacement = []
): array
Supports (PHP 4 , PHP 5, PHP 7, PHP 8)
Parameters
Parameter | Description |
array | target array |
offset |
If If |
length |
If If If If |
replacement | If replacement array is specified, then the removed elements are replaced with elements from this array. |
Return Value
returns the sliced array
Example
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>
Output
array(2) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(6) "yellow"
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(6) "orange"
}
array(5) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
[3]=>
string(5) "black"
[4]=>
string(6) "maroon"
}