Monday 26 August 2013

PHP Function array_splice()

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.

Paramters

ParameterDescription
inputRequired. Specifies an array
offsetRequired. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array.
lengthOptional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will remove all elements, starting from the position set by the start-parameter. 
replacementOptional. Specifies an array with the elements that will be insertet to the original array. If it's only one element, it can be a string, and does not have to be an 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", "green", "blue", "yellow");
array_splice($input, 2);
print_r($input);
print_r("<br />

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
print_r($input);
print_r("<br />

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
print_r($input);
print_r("<br />

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

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
print_r($input);
print_r("<br />

?> 
This will produce following result:
Array ( [0]=>red [1] =>green )
Array ( [0]=>red [1] =>yellow )
Array ( [0]=>red [1] =>orange )
Array ( [0]=>red [1] =>green [2]=>blue [3]=>black [4]=>maroon )
Array ( [0]=>red [1] =>green [2]=>blue [3]=>purple [4]=>yellow ) 

No comments:

Post a Comment