The array_splice Function
The array_splice
function cuts out and returns
a portion of an array. The removed portion
disappears from the original array. New elements
can be inserted in place of the removed portion.
The first parameter specifies the array to be spliced. The second parameter specifies the starting element for cutting, and the third - how many elements to cut. The third parameter can be negative - in this case the count will start from the end (-1 - the last element, -2 - the second to last, and so on). The third parameter can be omitted entirely - in this case the array will be cut to the very end.
The last optional parameter can define an array of elements that will be inserted to replace the removed ones.
Syntax
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array
Example
Let's cut out elements starting from the first (has
index 0), 3
pieces:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, 0, 3);
var_dump($res);
?>
The code execution result:
['a', 'b', 'c']
At the same time, the $arr array will become:
['d', 'e']
Example
Let's cut out elements starting from the second (has
index 1), 3
pieces:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, 1, 3);
var_dump($res);
?>
The code execution result:
['b', 'c', 'd']
At the same time, the $arr array will become:
['a', 'e']
Example
Let's cut out elements starting from the second (has index 1) to the end of the array. For this, the third parameter is omitted:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, 1);
var_dump($res);
?>
The code execution result:
['b', 'c', 'd', 'e']
At the same time, the $arr array will become:
['a']
Example
Let's cut out elements starting from the second to last,
2
pieces. For this, the second parameter
is set to -2
(the position of the second to last
element):
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, -2, 2);
var_dump($res);
?>
The code execution result:
['d', 'e']
At the same time, the $arr array will become:
['a', 'b', 'c']
Example
Let's cut out elements starting from the second (has
index 1), 2
pieces, and in their place insert
elements 1
, 2
, 3
:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, 1, 2, [1, 2, 3]);
var_dump($res);
?>
The code execution result:
['b', 'c']
At the same time, the $arr array will become:
['a', 1, 2, 3, 'd', 'e']
Example
Let's not cut out anything at all,
and simply insert elements 1
, 2
,
3
starting from position 1
. For
this, the third parameter is set to zero:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_splice($arr, 1, 0, [1, 2, 3]);
var_dump($res);
?>
The code execution result:
[]
At the same time, the $arr array will become:
['a', 1, 2, 3, 'b', 'c', 'd', 'e']
See Also
-
the
array_slice
function,
which cuts a portion of an array without changing the original array