Computer >> Computer tutorials >  >> Programming >> PHP

array_splice() function in PHP


The array_splice() function removes and replaces specified elements of an array. It returns the array consisting of the extracted elements.

Syntax

array_splice(arr1, begin, len, arr2)

Parameters

  • arr1 − The specified array.

  • begin − Where the removing of elements begin. Here, 0 is the first element, whereas a negative number states the beginning from the last element. -2 means start at the second last element of the array.

  • len − Specifies the number of elements to be removed. It also sets the length of the returned array.

  • arr2 − This is an array with the elements to be inserted to the original array. To insert only a single value, just specify only that value, and you do not need to specify the entire array.

Return

The array_splice() function returns the array consisting of the extracted elements

Example

The following is an example −

<?php
$arr1 = array("mac", "windows", "linux");
array_splice($arr1, 2);
print_r($arr1);
?>

Output

Array (
   [0] => mac
   [1] => windows
)

Example

Let us see another example −

<?php
$arr1 = array("accessories", "tablet", "laptop", "mobile");
array_splice($arr1, 3, 0, "desktop");
print_r($arr1);
?>

Output

Array (
   [0] => accessories
   [1] => tablet
   [2] => laptop
   [3] => desktop
   [4] => mobile
)