array_splice() removes or replaces a section of an array and modifies the original array. It can also insert replacement values at the selected position.
$items = ['A', 'B', 'C', 'D'];
$removed = array_splice($items, 1, 2, ['X']);
print_r($items);
print_r($removed);Because array_splice() changes the input array, copy the array first when you need to preserve the original.
The array_splice() function in PHP is used to remove, replace, or insert elements in an array. It modifies the original array, making it a versatile tool for array manipulation.
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = [])
$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 1, 2);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => date
)
$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 1, 2, ['mango', 'peach']);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => mango
[2] => peach
[3] => date
)
$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 2, 0, ['grape', 'kiwi']);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => grape
[3] => kiwi
[4] => cherry
[5] => date
)
$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 2);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
)
The array_splice() function is a powerful tool for modifying arrays in PHP. Whether you need to remove, replace, or insert elements at specific positions, this function offers flexibility while modifying the original array directly.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.