Latest web development tutorials

PHP array_splice () function

PHP Array Reference Complete PHP Array Reference

Examples

Remove elements from an array, and replace it with a new element:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>

Running instance »

Definition and Usage

array_splice () function removes the selected element from an array and replace it with a new element. The function also returns an array of elements to be removed.

Tip: If the function does not remove any elements (length = 0), then replace the array of parameters from the start position of the insertion (see Example 2).

NOTE: Do not substitute retention array keys.


grammar

array_splice( array,start,length,array )

参数 描述
array 必需。规定数组。
start 必需。数值。规定删除元素的开始位置。 0 = 第一个元素。 如果该值设置为正数,则从数组中该值指定的偏移量开始移除。如果该值设置为负数,则从数组末端倒数该值指定的偏移量开始移除。 -2 意味着从数组的倒数第二个元素开始。
length 可选。数值。规定被移除的元素个数,也是被返回数组的长度。 如果该值设置为正数,则移除该数量的元素。如果该值设置为负数,则移除从 start 到数组末端倒数 length 为止中间所有的元素。如果该值未设置,则移除从 start 参数设置的位置开始直到数组末端的所有元素。
array 可选。规定带有要插入原始数组中元素的数组。如果只有一个元素,则可以设置为字符串,不需要设置为数组。

technical details

return value: It returns an array containing the extracted elements.
PHP version: 4+


More examples

Example 1

Example front part of the same page, but the output returned array:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>

Running instance »

Example 2

With a set length of parameter 0:

<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>

Running instance »


PHP Array Reference Complete PHP Array Reference