Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

array_splice

Description

The array_splice of Array for PHP remove a portion of the array and replace it with something else.

Syntax

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

Parameters

array

The input array.

offset

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

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

length

If length is omitted, everything is removed 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 zero, no elements will be removed.

replacement

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.

If replacement is just one element it is not necessary to put array() or square brackets around it, unless the element is an array itself, an object or null.

Note: Keys in the replacement array are not preserved.

Return

Returns an array consisting of the extracted elements.

Examples

1 · array offset · Negative

<?

$array = array("a", "b", "c", "d", "e");
$offset = -1;

$return = array_splice($array, $offset);

print_r($return);

?>
Array
(
    [0] => e
)

2 · array offset · Positive

<?

$array = array("a", "b", "c", "d", "e");
$offset = 1;

$return = array_splice($array, $offset);

print_r($return);

?>
Array
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)

3 · length · Negative

<?

$array = array("a", "b", "c", "d", "e");
$offset = 0;
$length = -1;

$return = array_splice($array, $offset, $length);

print_r($return);

?>
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

4 · length · Zero

<?

$array = array("a", "b", "c", "d", "e");
$offset = 0;
$length = 0;

$return = array_splice($array, $offset, $length);

print_r($return);

?>
Array
(
)

5 · length · Positive

<?

$array = array("a", "b", "c", "d", "e");
$offset = 0;
$length = 1;

$return = array_splice($array, $offset, $length);

print_r($return);

?>
Array
(
    [0] => a
)

6 · replacement

<?

$array = array("a", "b", "c", "d", "e");
$offset = 0;
$length = 1;
$replacement = array("f", "g");

$return = array_splice($array, $offset, $length, $replacement);

print_r($return);
print_r($array);

?>
Array
(
    [0] => a
)
Array
(
    [0] => f
    [1] => g
    [2] => b
    [3] => c
    [4] => d
    [5] => e
)
HomeMenu