PHP Manual
Prev |  | Next

# array_splice

array_splice -- Remove a portion of the array and replace it with something else

## Description

`array array_splice`(array input, int offset, int [length] , array [replacement] );

array_splice() removed the elements designated by `offset` and `length` from the `input` array, and replaces them with the elements of the `replacement` array, if supplied.

If `offset` is positive then the start of removed portion is at that offset from the beginning of the `input` array. If `offset` is negative then it starts that far from the end of the `input` array.

If `length` is omitted, removes everything from `offset` to the end of the array. If `length` is specified and is positive, then that many elements will be removed. If `length` is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from `offset` to the end of the array when `replacement` is also specified, use `count($input)` for `length`.

If `replacement` array is specified, then the removed elements are replaced with elements from this array. If `offset` and `length` are such that nothing is removed, then the elements from the `replacement` array are inserted in the place specified by the `offset`. Tip: if the replacement is just one element it is not necessary to put `array()` around it, unless the element is an array itself.

The following equivalences hold:

      1
      2 array_push($input, $x, $y)     array_splice($input, count($input), 0, array($x, $y))
      3 array_pop($input)              array_splice($input, -1)
      4 array_shift($input)            array_splice($input, 0, 1)
      5 array_unshift($input, $x, $y)  array_splice($input, 0, 0, array($x, $y))
      6 $a[$x] = $y                    array_splice($input, $x, 1, $y)
      7

Returns the array consisting of removed elements.

Example 1. array_splice() examples

      1
      2 $input = array("red", "green", "blue", "yellow");
      3
      4 array_splice($input, 2);      // $input is now array("red", "green")
      5 array_splice($input, 1, -1);  // $input is now array("red", "yellow")
      6 array_splice($input, 1, count($input), "orange");
      7                               // $input is now array("red", "orange")
      8 array_splice($input, -1, 1, array("black", "maroon"));
      9                               // $input is now array("red", "green",
     10                               //          "blue", "black", "maroon")
     11

See also array_slice().

> Note: This function was added in PHP 4.0.

Prev | Home | Next
array_slice | Up | array_unshift