How to Use the PHP array_splice() Function
In this article, you will learn how to use the PHP array_splice() function.
PHP array_splice() Function
The array_splice() function in PHP is used to remove elements from an array and replace them with new elements (if specified).
array_splice(array &$input, int $offset, int $length = null, mixed $replacement = array()) : array
$input: The input array. Note that the input array is passed by reference and will be modified by the function.
$offset: The index at which to start changing the array.
$length: (optional) The number of elements to remove. If $length is omitted, array_splice() will remove all elements from $offset to the end of the array.
$replacement: (optional) The elements to add to the array.
<?php $fruits = array("apple", "banana", "cherry", "durian"); array_splice($fruits, 1, 2, array("mango", "orange")); print_r($fruits); //Output: //Array //( //  => apple //  => mango //  => orange //  => durian //) ?>
In the above example, array_splice() removes two elements (“banana” and “cherry”) starting from the second index (1), and replaces them with two new elements (“mango” and “orange”).
It’s important to note that array_splice() returns the removed elements as an array. You can store this result in a separate array if you need to use it later:
<?php $removed_fruits = array_splice($fruits, 1, 2, array("mango", "orange")); print_r($removed_fruits); //Output: //Array //( //  => banana //  => cherry //) ?>
Also, if you don’t want to replace the removed elements with new elements, you can simply omit the $replacement argument:
<?php $removed_fruits = array_splice($fruits, 1, 2); print_r($removed_fruits); //Output: //Array //( //  => banana //  => cherry //) ?>
So, in conclusion, array_splice() is a useful function for removing and replacing elements in an array in one operation, and can simplify your code if you need to make multiple changes to an array.