array_splice
Removes part of an array and optionally inserts new elements in its place.
Syntax
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being modified. |
| $offset | int | The position to start at. |
| $length | ?int | Optional. How many elements to remove. |
| $replacement | mixed | Optional. What to insert in place of the removed ones. |
Return value
arrayThe removed elements.
Examples
Removing an element from the middle:
<?php
$letters = ['a', 'b', 'c', 'd'];
$removed = array_splice($letters, 1, 2);
echo implode('', $letters), ' | ', implode('', $removed);Output:
ad | bcInserting without removing:
<?php
$letters = ['a', 'd'];
array_splice($letters, 1, 0, ['b', 'c']);
echo implode('', $letters);Output:
abcdNotes
Do not confuse it with array_slice(), which returns part of an array and leaves the original untouched.
See also
- array_slice — Returns part of an array.
- array_push — Appends elements to the end of an array.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.