Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_splice() function

Reference for PHP array_splice(): remove, replace or insert elements in an array in place, what it returns, and how it renumbers keys.

array_splice() changes an array in place. It can remove a range of elements, replace that range with other values, or insert new values without removing anything.

The function returns the elements it removed, and the array you pass in is modified directly because it is taken by reference. Numeric keys of the modified array are renumbered; string keys are kept.

PHP
<?php
$list = ["a", "b", "c", "d"];
$removed = array_splice($list, 1, 2);
// $list is ["a", "d"], $removed is ["b", "c"]

Try it

PHP Remove, replace and insert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Keys and a negative length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_splice(
    array &$array,
    int $offset,
    ?int $length = null,
    mixed $replacement = []
): array
Name Description
&$array The array to change, passed by reference.
$offset Where removal starts. A negative value counts from the end.
$length How many elements to remove. A negative value stops that many elements before the end. null removes everything from the offset to the end. 0 removes nothing.
$replacement Elements to put in place of the removed ones. A single non-array value is treated as a one-element array.

Return value: an array of the removed elements (empty if none were removed).

Usage notes

  • It modifies the original. If you only want a copy of part of an array, use array_slice().
  • Inserting: use a length of 0. The new elements appear before the element at $offset.
  • Keys of the replacement are ignored. The inserted values get fresh numeric keys.
  • Numeric keys are renumbered in the modified array; string keys survive. The returned array of removed elements is also renumbered.
  • Replacing with null: a bare null replacement is cast to an empty array and so removes the range; wrap it as [null] to insert a null value.
  • Removing one element by key in an associative array is simpler with unset().
  • Queues and stacks: array_shift(), array_pop() and their partners cover the ends of an array more directly.