Home >>PHP Array Functions >PHP array_splice() Function
PHP array_splice() function is used to replace the existing element of the given input array with elements from other arrays and returns an array of removed or replaced elements. It can accept up to four parameters $array, $start, $length, $array. It returns an array of the removed elements from $start to $length.
Syntax:
array_splice($array, $start, $length, $array);
Parameter | Description |
---|---|
array | This is a required parameter. This parameter defines the given array. |
start | This is a required parameter. This parameter defines where the function will start removing elements. |
length | This is an optional parameter. This parameter defines how many elements will be removed and also length of the returned array. |
array | This is an optional parameter. This parameter defines an array with the elements that will be inserted to the original array. |
Here is an example of array_splice() function in PHP:
<body> <pre> <?php $x=array("A","B","C","D","E","F","G"); $y=array("X","Y","Z"); array_splice($x,0,2,$y); print_r($x); ?> </pre> </body> </html>
Array ( [0] => X [1] => Y [2] => Z [3] => C [4] => D [5] => E [6] => F [7] => G )
Example 2:
<html> <body> <pre> <?php $x=array("A","B","C","D","E","F","G"); $y=array("X","Y","Z","Q","W"); print_r(array_splice($x,1,2,$y)); print_r($x); ?> </pre> </body> </html>
Array ( [0] => B [1] => C ) Array ( [0] => A [1] => X [2] => Y [3] => Z [4] => Q [5] => W [6] => D [7] => E [8] => F [9] => G )