array_splice()

array_splice() — Remove a portion of the array and replace it with something else.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Removes the elements designated by offset and length from the array array, and replaces them with the elements of the replacement array, if supplied.

Signature

array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array

Parameters

ParameterTypeWhat it takes
&$arrayarrayThe input array.
$offsetintIf offset is positive then the start of the removed portion is at that offset from the beginning of the array array.
$length?intIf length is omitted, removes everything from offset to the end of the array.
$replacementmixedIf replacement array is specified, then the removed elements are replaced with elements from this array.

Return value

Returns an array consisting of the extracted elements.

Example

A runnable snippet:

$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" }

Changelog

VersionChange
8.0.0length is nullable now.

See also

array_merge(), array_slice()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_splice() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.