PHP - Function array_splice()


Advertisements


Syntax

array_splice ( $input, $offset [,$length [,$replacement]] );

Definition and Usage

This function removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. It returns an array containing the extracted elements.

Parameters

Sr.No Parameter & Description
1

input(Required)

It specifies an array

2

offset

It specifies where the function will start removing elements. 0 = the first element.

3

length(Optional)

It specifies how many elements will be removed, and also length of the returned array.

4

replacement(Optional)

It specifies an array with the elements that will be inserted to the original array.

Return Values

It returns the last value of the array, shortening the array by one element.

Example

Try out following example −

<?php
   $input = array("red", "black", "pink", "white");
   array_splice($input, 2);
   print_r($input);
   print_r("<br />");

   $input = array("red", "black", "pink", "white");
   array_splice($input, 1, -1);
   print_r($input);
   print_r("<br />");

   $input = array("red", "black", "pink", "white");
   array_splice($input, 1, count($input), "orange");
   print_r($input);
   print_r("<br />");

   $input = array("red", "black", "pink", "white");
   array_splice($input, -1, 1, array("black", "maroon"));
   print_r($input);
   print_r("<br />");

   $input = array("red", "black", "pink", "white");
   array_splice($input, 3, 0, "purple");
   print_r($input);
   print_r("<br />");

?> 

This will produce the following result −

Array ( [0]=>red [1] =>black )
Array ( [0]=>red [1] =>white )
Array ( [0]=>red [1] =>orange )
Array ( [0]=>red [1] =>black [2]=>pink [3]=>black [4]=>maroon )
Array ( [0]=>red [1] =>black [2]=>pink [3]=>purple [4]=>white ) 

php_function_reference.htm

Advertisements