Tutorialspoint.dev

PHP | array_splice() Function

This inbuilt function of PHP is an advanced and extended version of array_slice() function, where we not only can remove elements from an array but can also add other elements to the array. The function generally replaces the existing element with elements from other arrays and returns an array of removed or replaced elements.

Syntax:

array array_splice($array1, $start_point, $range, $array2)

Parameters: This function can take four parameters and are described below:

  1. $array1 (mandatory): This parameter refers to the original array, we want to operate upon.
  2. $start_point (mandatory): This parameter refers to the starting position of the array from where the elements need to be removed. It is mandatory to supply this value. If the value supplied is negative, then the function starts removing from the end of the array, i.e., -1 refers to the last element of the array.
  3. $range (optional): This parameter refers to the range or limit point up to which the removal is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will remove all the values as mentioned in the starting point right up to the end.
  4. $array2 (optional): This refers to another array whose elements are to be inserted into $array1. Now for insertion of one element, we don’t need to provide the whole array. We can just pass a single string for one value. For group of values, we need an array.

Return Value: The function will return an array of the removed elements from $start_point to $range.

Below program illustrate the array_splice() function in PHP:

<?php
  
// PHP program to illustrate the use 
// of array_splice() function
  
$array1 = array("10"=>"raghav", "20"=>"ram"
    "30"=>"laxman","40"=>"aakash","50"=>"ravi");
  
$array2 = array("60"=>"ankita","70"=>"antara");
  
echo "The returned array: ";
print_r(array_splice($array1, 1, 4, $array2));
  
echo " The original array is modified to: ";
print_r($array1);
  
?>

Output:

The returned array: 
Array
(
    [0] => ram
    [1] => laxman
    [2] => aakash
    [3] => ravi
)

The original array is modified to: 
Array
(
    [0] => raghav
    [1] => ankita
    [2] => antara
)

Reference:
http://php.net/manual/en/function.array-splice.php



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter