PHP » Arrays » array_splice()

Syntax:
array array_splice(array array, int start [, int length [, array new_data]])
array
Array to have a portion removed or replaced.
start
Start position for removed or replaced portion.
length
Length or end position for removed or replaced portion.
new_data
Data to replace the removed portion.

Replaces part of an array with another array.

array_splice() removes part of an array and, if provided, replacement data is put in its place. An array consisting of the removed elements is returned. Unlike array_slice(), the array passed to array_splice() is modified by the function.

If start is a positive number, it means that the part to be removed will start that many elements from the beginning of the array. A negative start will offset the start that many elements from the end of the array instead, the last element being -1. If the length parameter is omitted, the rest of the array is removed. Otherwise, a positive value specifies a maximum length for the removed portion. A negative value, on the other hand, specifies a stop element, counted from the back of the array. In this case, the last element counts as 0.

Examples

Code:
<?php

function element_print($value)
{
   print "$value ";
}

$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// replace the five first elements with three zeros
array_walk(array_splice($array1, 0, 5, array(0, 0, 0)), "element_print");
print "<br>";
array_walk($array1, "element_print");
print "<br><br>";

$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// replace the three last elements with three zeros
array_walk(array_splice($array1, -3, 3, array(0, 0, 0)), "element_print");
print "<br>";
array_walk($array1, "element_print");
print "<br><br>";

$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// remove the last three elements
array_walk(array_splice($array1, -3), "element_print");
print "<br>";
array_walk($array1, "element_print");

?>
Output:
1 2 3 4 5
0 0 0 6 7 8 9

7 8 9
1 2 3 4 5 6 0 0 0

7 8 9
1 2 3 4 5 6
Explanation:

The example shows three different combinations of parameters for array_splice(). For each combination, the first line printed is the removed portion, and the second line is the modified array.

See Also: