Array slice and splice help you take parts of an array or change it by adding or removing items.
Array slice and splice in PHP
<?php // Array slice syntax $sliced_array = array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false); // Array splice syntax $removed_elements = array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []); ?>
array_slice returns a new array and does not change the original array.
array_splice changes the original array by removing and optionally adding elements.
<?php // Example 1: Slice part of an array $fruits = ['apple', 'banana', 'cherry', 'date']; $sliced = array_slice($fruits, 1, 2); print_r($sliced);
<?php // Example 2: Slice with offset only $numbers = [10, 20, 30, 40]; $sliced = array_slice($numbers, 2); print_r($sliced);
<?php // Example 3: Splice to remove elements $colors = ['red', 'green', 'blue', 'yellow']; $removed = array_splice($colors, 1, 2); print_r($colors); print_r($removed);
<?php // Example 4: Splice to replace elements $letters = ['a', 'b', 'c', 'd']; array_splice($letters, 1, 2, ['x', 'y']); print_r($letters);
This program shows how array_slice returns a new part without changing the original array. Then it shows how array_splice removes some elements and adds new ones, changing the original array.
<?php // Create an array $animals = ['cat', 'dog', 'bird', 'fish', 'horse']; // Print original array echo "Original array:\n"; print_r($animals); // Use array_slice to get a part without changing original $sliced_animals = array_slice($animals, 1, 3); echo "\nSliced array (index 1 to 3):\n"; print_r($sliced_animals); echo "\nArray after slice (unchanged):\n"; print_r($animals); // Use array_splice to remove and replace elements $removed_animals = array_splice($animals, 2, 2, ['lion', 'tiger']); echo "\nRemoved elements by splice:\n"; print_r($removed_animals); echo "\nArray after splice (changed):\n"; print_r($animals); ?>
Time complexity: array_slice is O(n) where n is the length of the slice; array_splice is O(m) where m is the number of elements removed or added.
Space complexity: array_slice creates a new array, so it uses extra space; array_splice modifies in place, so uses less extra space.
Common mistake: Expecting array_splice to return the changed array. It returns the removed elements instead.
Use array_slice when you want a copy of part of the array without changing the original. Use array_splice when you want to change the original array by removing or adding items.
array_slice returns a new array with selected elements and does not change the original.
array_splice removes and/or adds elements in the original array and returns the removed elements.
Use slice to copy parts, splice to change the array.