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 ); ?> |
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