AppDividend
Latest Code Tutorials

PHP Array Splice: How to Slice Array in PHP

The array_splice() function removes the selected elements from the array and replaces them with the new elements. The function also returns the array with the removed elements.

PHP Array Splice

PHP array_splice() is a built-in function used to get the array by slicing through it based on the users’ requirements. The array_splice() function removes a portion of the array and replaces it with provided argument.

Syntax

The syntax of php array_splice() method is following.

array_splice(array,start,length,array)

Parameters

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. Specify how many elements will be removed and the returned array’s length. 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 inserted into the original array.

Example

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

See the following example of PHP array_slice() example.

<?php

// app.php

$deadCharacters=array("Lyana","Edd","melisandre","Jorah");
$aliveCharacters=array("Jon","Daenerys");
print_r(array_splice($deadCharacters , 0, 2, $aliveCharacters));
print_r($deadCharacters);

The output is the following.

PHP Array Splice Example

See some more examples.

<?php

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

The output is the following.

array_splice() examples

PHP array_splice() function 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 maintain the array’s ordering 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 the key “0”. It preserves numeric keys. Note that the function does not reference the original array but returns a new array.

Conclusively, PHP Array Splice Example 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.