Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. array_splice() / array_slice()

array_splice() / array_slice() Since: PHP 4(2000)

Removes, inserts, or replaces elements at any position in an array, or extracts a portion of an array.

Syntax

// Removes, inserts, or replaces elements at the specified position in an array.
array_splice(array, offset, length, replacement);

// Extracts a portion of an array and returns it as a new array.
array_slice(array, offset, length, preserve_keys);

Function List

FunctionDescription
array_splice($array, $offset, $length, $replacement)Removes elements from the specified position in an array and optionally inserts new elements in their place. Returns the removed elements as an array. The original array is modified.
array_slice($array, $offset, $length, $preserve_keys)Extracts a specified number of elements starting at the given position and returns them as a new array. The original array is not modified.

Sample Code

<?php
$colors = ['red', 'blue', 'green', 'yellow', 'purple'];

// Extracts 2 elements starting at index 1. The original array is unchanged.
$sliced = array_slice($colors, 1, 2);
print_r($sliced); // Returns an array of ['blue', 'green'].

// Uses a negative offset to extract from the end.
$last_two = array_slice($colors, -2);
print_r($last_two); // Returns an array of ['yellow', 'purple'].

// Extracts elements while preserving the original keys.
$preserved = array_slice($colors, 2, 2, true);
print_r($preserved); // Keys are preserved as [2 => 'green', 3 => 'yellow'].

// Removes 2 elements starting at index 1 and inserts new elements.
$items = ['A', 'B', 'C', 'D', 'E'];
$removed = array_splice($items, 1, 2, ['X', 'Y', 'Z']);
print_r($removed); // Returns the removed elements ['B', 'C'].
print_r($items); // The array becomes ['A', 'X', 'Y', 'Z', 'D', 'E'].

// Inserts elements without removing any.
$list = ['Mon', 'Wed', 'Fri'];
array_splice($list, 1, 0, ['Tue']);
print_r($list); // The array becomes ['Mon', 'Tue', 'Wed', 'Fri'].

Notes

array_splice() is a destructive function that modifies the original array directly. It can delete, insert, and replace elements in a single call. Passing 0 as the third argument inserts without removing; omitting the fourth argument removes without inserting.

array_slice() is a non-destructive function that does not modify the original array. Passing true as the fourth argument preserves the original keys. By default, numeric keys are reindexed starting from 0, so specify true when key values are important.

If you only need to add or remove elements at the beginning or end of an array, array_push() / array_pop() / array_shift() / array_unshift() offer a simpler approach.

If you find any errors or copyright issues, please .