PHP 8 reference · Array Functions

PHP array_splice() Function

Remove a portion of an array and optionally replace it with other elements, changing the array in place.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The array (changed in place).
offset Where to start; negative counts from the end.
length optional How many to remove; 0 removes none (to insert).
replacement optional Elements to insert in their place. Default: []

Return value

The removed elements.

Examples

Remove elementsTry it yourself
<?php
$colors = ["red", "green", "blue", "yellow"];
$removed = array_splice($colors, 1, 2);
print_r($removed);
print_r($colors);

Output

Array
(
    [0] => green
    [1] => blue
)
Array
(
    [0] => red
    [1] => yellow
)
Insert in the middleTry it yourself
<?php
$steps = ["start", "finish"];
array_splice($steps, 1, 0, ["middle"]); // insert without removing
print_r($steps);

Output

Array
(
    [0] => start
    [1] => middle
    [2] => finish
)

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?