PHP array_splice() function

PHP array_udiff_assoc() function
PHP array_udiff_uassoc() function

The array_splice function performs two functionalities

  1. Removes specified elements from an array.
  2. Replace the removed elements with new elements.

If array_splice does not remove any element from the array in case of length = 0, then the new elements will be inserted at the position specified by the start parameter.

Remember, the keys in the output array are not preserved.

What is the syntax of the array_splice function in PHP?

barray_splice(array, start, length, array)
ParameterDescription
arrayThe array from which the elements are to be removed and replaced – Required
startDefine the starting position for removing the elements.
If set to 0, the elements will be removed from the starting position of the array.
If set to a negative number, the position for removing elements will be from the right side of the array. For example, -2 means start removing elements from the second last element of the array.
lengthDefine the number of elements to remove and the length of the returned array.
If set to a negative number, it starts its action from the right to the left side of the array.
If not set, remove all the elements and insert new elements starring from the position of the start parameter.
– Optional
arrayDefines the new elements to be inserted in the place of removed elements. Can be an array, a string, or a single element – Optional
array_splice function in PHP

Examples of array_splice function

Example 1. Remove elements from an array and replace them with new elements.

<?php
$array_1=array("a"=>"R","b"=>"G","c"=>"B","d"=>"Y");
$array_2=array("a"=>"P","b"=>"O");
array_splice($array_1,0,2,$array_2);
print_r($array_1);
?>

Example 2. Remove elements from an array and replace them with new elements where length is set to 0.

<?php
$array_1=array("0"=>"R","1"=>"G");
$array_2=array("0"=>"P","1"=>"O");
array_splice($array_1,1,1,0,$array_2);
print_r($array_1);
?>
PHP array_udiff_assoc() function
PHP array_udiff_uassoc() function
en English
X
Scroll to Top