PHP array_splice function

Last Updated: February 15, 2022

array_splice — Remove the portion of the array or replace portion of the array

Syntax

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

Supports (PHP 4 , PHP 5, PHP 7, PHP 8)

Parameters


Parameter Description
array target array
offset

If offset is positive then the start of the removed portion is at that offset from the beginning of the array array.

If offset is negative then the start of the removed portion is at that offset from the end of the array array.

length

If length is not there, removes everything from offset to the end of the array.

If length  is positive, then that many elements will be removed.

If length is negative, then the end of the removed portion will be that many elements from the end of the array.

If length is specified and is zero, no elements will be removed.

replacement If replacement array is specified, then the removed elements are replaced with elements from this array.

Return Value

returns the sliced array

Example


<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>

Output

array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "yellow"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "orange"
}
array(5) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(5) "black"
  [4]=>
  string(6) "maroon"
}
Test