How to use array_splice() Function In PHP

It is an advanced and extended version of the array_slice() function, where we not only 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.

Example 6: The array_splice() method will remove elements and add other elements according to the position parameters.

PHP




<?php
 
// PHP program to illustrate the use
// of array_splice() function
 
$array1 = [
    "1" => "Geeks",
    "2" => "for",
    "3" => "geeks",
    "4" => "is",
    "5" => "fun",
];
 
$array2 = ["6" => "are", "7" => "great"];
 
echo "The returned array: \n";
print_r(array_splice($array1, 1, 4, $array2));
 
echo "\nThe original array is modified to: \n";
print_r($array1);
 
?>


Output

The returned array: 
Array
(
    [0] => for
    [1] => geeks
    [2] => is
    [3] => fun
)

The original array is modified to: 
Array
(
    [0] => Geeks
    [1] => are
    [2] => great
)



How to Insert a New Element in an Array in PHP ?

In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.

We can insert an element or item in an array using the below functions:

Table of Content

  • Using array_unshift() Function
  • Using array_push() Function
  • Using array_merge() Function
  • Using array_splice() Function

Similar Reads

Using array_unshift() Function

The array_unshift() Function is used to add one or more than one element at the beginning of the array. and these elements get inserted at the beginning of the array. because of the inserted elements or items in the array, the length of the array also gets increased by the number of elements inserted or added in the array. After inserting the elements, we can use the print_r() function to print the array information....

Using array_push() Function

...

Using array_merge() Function

...

Using array_splice() Function

The array_push() Function function is used to push new elements into an array. We can push one or more than one element into the array and these elements get inserted to the end of the array and because of the pushed elements into the array, the length of the array also gets incremented by the number of elements pushed into the array. After inserting the elements, we use the print_r() function to print the array information....