Difference Between array_slice and array_splice in PHP

In PHP, manipulating arrays is a fundamental task, and two functions that often cause confusion are array_slice() and array_splice(). While their names are remarkably similar, they serve entirely different purposes: array_slice() extracts a portion of an array without modifying the original, whereas array_splice() removes, replaces, or inserts elements, directly altering the original array. This article provides a clear, direct comparison of these two functions, detailing their syntax, behaviors, and key differences with practical examples.

array_slice(): The Non-Destructive Option

The array_slice() function is used to extract a specific portion (a slice) of an array. It is non-destructive, meaning it does not modify the original array; instead, it returns a new array containing the selected elements.

Syntax

array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

Example

$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
$slice = array_slice($fruits, 1, 3);

print_r($slice);  // Output: ['banana', 'cherry', 'date']
print_r($fruits); // Output: ['apple', 'banana', 'cherry', 'date', 'elderberry'] (Unchanged)

array_splice(): The Destructive Option

The array_splice() function is used to modify an array by removing, replacing, or inserting elements. This function is destructive because it alters the original array directly (passed by reference). It returns an array containing the elements that were removed.

Syntax

array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array

Example: Removing Elements

$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
$removed = array_splice($fruits, 1, 3);

print_r($removed); // Output: ['banana', 'cherry', 'date'] (The removed elements)
print_r($fruits);  // Output: ['apple', 'elderberry'] (The modified original array)

Example: Replacing Elements

$fruits = ['apple', 'banana', 'cherry'];
array_splice($fruits, 1, 1, ['blueberry', 'coconut']);

print_r($fruits); // Output: ['apple', 'blueberry', 'coconut', 'cherry']

Quick Comparison of Key Differences

Feature array_slice() array_splice()
Original Array Remains unchanged (Immutable) Is modified (Mutable / Passed by reference)
Return Value The extracted slice The removed elements
Main Use Case Reading/copying a subset of an array Deleting, replacing, or inserting elements
Key Preservation Optional via the fourth parameter Resets numeric keys in the modified array