PHP Array Splice Example | array_slice() Function Tutorial
PHP Array Splice Example | array_slice() Function Tutorial is today’s topic. PHP array_splice() function removes the elements from an array and replaces it with new elements. PHP array_slice() is the inbuilt function and is used to get the part of the array by slicing through it based on the users’ requirement. 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.
<?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 following.
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 following.
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.