PHP array_splice() Function

PHP array_splice() function is used to remove selected elements from an array and replace it with new elements. 

Syntax

array_splice(array1, start, length, array2)

Parameters

  1. array1(required): It specifies an array.
  2. start(required): It is a numeric value, and it specifies where the function will start removing elements: 0th index = the first element.
  3. length(optional): It is a numeric value and specifies 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.
  4. array2(optional): It specifies an array with the elements inserted into the original array.

Return value

This function returns an array of the removed elements from start to length.

Visual RepresentationVisual Representation of PHP array_splice() Function

Example 1: How to Use array_splice() function

<?php

$arr1=array("A","B","C","D","E");

$arr2=array("X","Z");

echo "Removed Elements from arr1 : \n";
 
print_r(array_splice($arr1 , 1, 4, $arr2));

echo "Updated arr1 : \n";

print_r($arr1);

Output

Removed Elements from arr1 : 
Array
(
 [0] => B
 [1] => C
 [2] => D
 [3] => E
)
Updated arr1 : 
Array
(
 [0] => A
 [1] => X
 [2] => Z
)

Example 2: Using only required parametersVisual Representation of Using only required parameters

<?php

$arr1=array("A","B","C","D","E");

echo "Removed elements: \n";

print_r(array_splice($arr1,2));

echo "Updated original array : \n";

print_r($arr1);

Output

Removed elements: 
Array
(
 [0] => C
 [1] => D
 [2] => E
)
Updated original array : 
Array
(
 [0] => A
 [1] => B
)

In this example, the function removed elements from position 2 to the end of the array($arr1) since no length parameter is specified. As a result, the remaining array only contains “A” and “B”.

Example 3: Remove the last element of the arrayVisual Representation of Remove the last element of the array

<?php

$arr1=array("A","B","C","D","E");

echo "Removed Last element: \n";

print_r(array_splice($arr1,-1));

echo "Updated original array : \n";

print_r($arr1);

Output

Removed Last element: 
Array
(
 [0] => E
)
Updated original array : 
Array
(
 [0] => A
 [1] => B
 [2] => C
 [3] => D
)

In this example, the method is called with parameter -1. The -1 indicates the start position from the end of the array (i.e., the function starts removing elements from the last element of the array). Since no length is specified, only the last element (“E“) is removed.  As a result, the remaining array contains “A”, “B”, “C” and “D”.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.