How to Splice Array in PHP: Syntax and Examples
In PHP, you can splice an array using the
array_splice() function, which removes a portion of the array and optionally replaces it with new elements. It modifies the original array and returns the removed elements as a new array.Syntax
The array_splice() function has this syntax:
array_splice(array &array, int offset, int length = null, array replacement = [])
array: The original array to modify.
offset: The start position to remove elements (0-based index).
length: Number of elements to remove (optional).
replacement: Array of elements to insert at the offset (optional).
php
array_splice(array &$array, int $offset, ?int $length = null, array $replacement = []): array
Example
This example shows how to remove and replace elements in an array using array_splice(). It removes 2 elements starting at index 1 and inserts new elements instead.
php
<?php $fruits = ['apple', 'banana', 'cherry', 'date', 'fig']; $removed = array_splice($fruits, 1, 2, ['blueberry', 'coconut']); print_r($fruits); print_r($removed); ?>
Output
Array
(
[0] => apple
[1] => blueberry
[2] => coconut
[3] => date
[4] => fig
)
Array
(
[0] => banana
[1] => cherry
)
Common Pitfalls
Common mistakes when using array_splice() include:
- Using a negative
lengthwhich can cause unexpected removals. - Not passing the array by reference, so the original array won't change.
- Confusing
offsetwith array keys when keys are not sequential.
php
<?php // array_splice always modifies the original array passed by reference $numbers = [1, 2, 3, 4]; array_splice($numbers, 1, 2); print_r($numbers); // Output: Array ( [0] => 1 [1] => 4 ) ?>
Output
Array
(
[0] => 1
[1] => 4
)
Quick Reference
| Parameter | Description |
|---|---|
| array | The array to modify (passed by reference) |
| offset | Start index to remove elements (0-based) |
| length | Number of elements to remove (optional, default removes all elements from offset) |
| replacement | Array of elements to insert at offset (optional) |
Key Takeaways
Use
array_splice() to remove and replace parts of an array in PHP.The function modifies the original array and returns the removed elements.
Always pass the array by reference to see changes in the original array.
The offset is zero-based and can be negative to count from the end.
Be careful with the length parameter to avoid removing unintended elements.