PHP array_splice() function

Example

Remove elements from the 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 Instances

Definition and Usage

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

Tip:If the function does not remove any elements (length=0), then from start Insert the replaced array at the position of the parameters (see example 2).

Note:The keys in the replaced array are not retained.

Description

The array_splice() function is similar to array_slice() The function is similar, selecting a series of elements from the array, but it does not return them, instead, it deletes them and replaces them with other values.

If the fourth parameter is provided, the previously selected elements will be replaced by the array specified by the fourth parameter.

The resulting array will be returned.

Syntax

array_splice(array,start,length,array)
Parameters Description
array Required. Specifies the array.
start

Required. Numeric. Specifies the starting position of the element to be deleted.

  • 0 = the first element.
  • If the value is set to a positive number, elements will be removed starting from the offset specified by the value in the array.
  • If the value is set to a negative number, elements will be removed starting from the offset specified by the value from the end of the array.
  • -2 means starting from the second-to-last element of the array.
length

Optional. Numeric. Specifies the number of elements to be removed, which is also the length of the returned array.

  • If this value is set to a positive number, the specified number of elements are removed.
  • If this value is set to a negative number, all elements from the start to the end of the array minus the length of the last length elements 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.
array

Optional. Specifies an array that contains the elements to be inserted into the original array.

If only one element is present, it can be set as a string without being set as an array.

Technical Details

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

More Examples

Example 1

Similar to the example in the previous part of this page, but output 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 Instances

Example 2

Set the length parameter 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 Instances