0
0
PhpHow-ToBeginner · 3 min read

How to Use array_splice in PHP: Syntax and Examples

The array_splice function in PHP removes a portion of an array and can replace it with new elements. You specify the array, the start position, the length of elements to remove, and optionally the replacement array.
📐

Syntax

The array_splice function modifies an array by removing and optionally replacing elements.

  • array: The input array to modify.
  • offset: The start position to remove elements (0-based index).
  • length (optional): Number of elements to remove. If omitted, removes all from offset to end.
  • replacement (optional): An array of elements to insert at the offset.
php
array_splice(array &$array, int $offset, ?int $length = null, array $replacement = []): array
💻

Example

This example shows how to remove 2 elements starting from index 1 and replace them with new values.

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 include:

  • Using a negative offset without understanding it counts from the end.
  • Omitting the length parameter unintentionally removes all elements from the offset to the end.
  • Not passing an array as the replacement, which can cause unexpected results.

Always check the offset and length carefully to avoid removing more elements than intended.

php
<?php
// Wrong: Omitting length removes all elements from offset
$colors = ['red', 'green', 'blue', 'yellow'];
array_splice($colors, 1);
print_r($colors); // Only 'red' remains

// Right: Specify length to remove only 2 elements
$colors = ['red', 'green', 'blue', 'yellow'];
array_splice($colors, 1, 2);
print_r($colors); // 'red' and 'yellow' remain
?>
Output
Array ( [0] => red ) Array ( [0] => red [1] => yellow )
📊

Quick Reference

ParameterDescription
arrayThe array to modify (passed by reference)
offsetStart position to remove elements (0-based, negative counts from end)
lengthNumber of elements to remove (optional, default removes all from offset)
replacementArray of elements to insert at offset (optional)
Return valueArray of removed elements

Key Takeaways

array_splice modifies the original array by removing and optionally replacing elements.
Always specify the offset and length carefully to avoid removing unintended elements.
The function returns the removed elements as a new array.
Passing a replacement array inserts new elements at the removal position.
Negative offsets count from the end of the array.