Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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 = []): array

Parameters

ParameterTypeDescription
$arrayarrayThe array being modified.
$offsetintThe position to start at.
$length?intOptional. How many elements to remove.
$replacementmixedOptional. 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 | bc

Inserting without removing:

<?php
 
$letters = ['a', 'd'];
array_splice($letters, 1, 0, ['b', 'c']);
 
echo implode('', $letters);

Output:

abcd

Notes

Do not confuse it with array_slice(), which returns part of an array and leaves the original untouched.

See also

Related recipes

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.