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
Syntax
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array
Parameters
| Parameter | Description |
|---|---|
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
<?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
)<?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
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
array.splice()· JavaScript
Related
array_slice()· Return a portion of an array without changing the original, given an offset and an optional length.array_shift()· Remove the first element of an array and return it. Numeric keys are renumbered from 0; string keys stay.- PHP Arrays · tutorial
- PHP Array Functions · tutorial