PHP array_splice() Function

Quick summary: The PHP array_splice() function removes or replaces elements in an array.

PHP array_splice() Syntax

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

PHP array_splice() Basic examples

$arr = [1,2,3,4];
array_splice($arr, 1, 2);
var_dump($arr);
PHP
Output:
array(2) {
  [0]=> int(1)
  [1]=> int(4)
}

Removes elements from the array.

PHP array_splice() Real-world usage

$queue = ['a','b','c'];
$next = array_splice($queue, 0, 1);
var_dump($next);
var_dump($queue);
PHP
Output:
array(1) { [0]=> string(1) "a" }
array(2) { [0]=> string(1) "b" [1]=> string(1) "c" }

Implements queue behavior.

PHP array_splice() Edge cases

$arr = [1,2];
array_splice($arr, 5, 1);
var_dump($arr);
PHP
Output:
array(2) {
  [0]=> int(1)
  [1]=> int(2)
}

Out-of-range offsets do not modify the array.

PHP array_splice() Common mistakes

Forgetting that array_splice modifies the array

array_splice works by reference.

Incorrect
array_splice([1,2,3],1);
Correct
$arr=[1,2,3]; array_splice($arr,1);

Pass a variable, not a literal.

PHP array_splice() Frequently Asked Questions

What does array_splice() do?

array_splice() removes a portion of an array and optionally replaces it.

Does array_splice() modify the original array?

Yes, it modifies the array in place.

What does array_splice() return?

It returns the removed portion.

Can array_splice() insert elements?

Yes, using the replacement parameter.

Supports negative offset?

Yes.

Preserves keys?

No, keys are reindexed.

Use case?

Removing or replacing parts of arrays.

Difference from array_slice()?

array_splice() modifies array, array_slice() does not.

Works with associative arrays?

Yes, but keys may reset.

Performance?

Depends on array size.

Can remove all elements?

Yes.

Alternative?

Manual array manipulation.

PHP array_splice() Related PHP Functions