Latest Code Tutorials

PHP Array Splice Example | array_splice() Function Tutorial


PHP array_splice() is the inbuilt function and is used to get the part of the array by slicing through it based on the users’ requirements. The array_splice() function removes the selected elements from the array and replaces it with the new elements. The function also returns the array with the removed elements.

PHP Array Splice Example

It removes a portion of the array and replaces it with something else.

The syntax of php array_splice() method is following.


An array parameter is required, and it specifies an array.

The start parameter is required, and it is a numeric value and it specifies where the function will start removing elements. 0th index = the first element.

The length parameter is optional, and it is a numeric value. Specifies how many elements will be removed, and also the length of the returned array. If this value is set to a negative number, the function will stop that far from the last element.

The last array parameter is optional and specifies an array with the elements that will be inserted to the original array.

PHP array_splice() method eturns the array consisting of the extracted elements.

See the following example of PHP array_slice() example.


// app.php

print_r(array_splice($deadCharacters , 0, 2, $aliveCharacters));

The output is following.

PHP Array Splice Example


See some more examples.


$mediaStocks = array("netflix", "disney", "at&t", "comcast");
$extractedStocks = array_splice($mediaStocks, 2);

The output is following.

array_splice() examples


PHP array_splice, split an array into two arrays. The returned arrays are the 2nd argument actually, and the used array, e.g. $input here contains the 1st argument of a collection.

When trying to splice an associative array into another, array_splice is missing two key ingredients:
  1) A string key for identifying the offset.
  2) The ability to preserve keys in the replacement array.

It is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

You cannot insert with array_splice an array with your key. The array_splice will always add it with the key “0”. It preserves numeric keys. Note that the function does not use a reference to the original array but returns a new array.

Conclusively, PHP Array Splice Example | array_slice() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.