PHP array_splice()Functions

PHP Array ReferenceComplete PHP Array Reference

Examples

Remove elements from an array and replace them with new elements:

<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); array_splice($a1,0,2,$a2); print_r($a1); ?>

Run example »

Definition and Usage

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

Tip:If the function does not remove any elements (length=0), the replacement array will be inserted from the position of the start parameter (see Example 2).

Note:Key names in the replacement array are not preserved.


Syntax

array_splice(array1,start,length,array2)

Parameter Description
array1 Required. Specifies the array.
start Required. Numeric value. Specifies the starting position for removing elements. 0 = the first element. If the value is set to positive, removal starts from the offset specified by this value in the array. If the value is set to negative, removal starts from the offset counted backward from the end of the array. -2 means starting from the second element from the end of the array.
length Optional. Numeric value. Specifies the number of elements to be removed, and also the length of the returned array. If this value is set to positive, that number of elements is removed. If this value is set to negative, all elements from start to the element that is length from the end of the array are removed. If this value is not set, all elements from the position set by the start parameter to the end of the array are removed.
array2 Optional. Specifies an array with the elements to be inserted into the original array. If there is only one element, it can be set as a string without needing to be set as an array.

Technical Details

Return Value: Returns an array containing the extracted elements.
PHP Version: 4+


More Examples

Example 1

Same as the example earlier on this page, but outputs the returned array:

<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); print_r(array_splice($a1,0,2,$a2)); ?>

Run example »

Example 2

With the length parameter set to 0:

<?php $a1=array("0"=>"red","1"=>"green"); $a2=array("0"=>"purple","1"=>"orange"); array_splice($a1,1,0,$a2); print_r($a1); ?>

Run example »


PHP Array ReferenceComplete PHP Array Reference Other Extensions