PHP array_splice() 函数

实例

从数组中移除元素,并用新元素取代它:

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

Run Instance

定义和用法

array_splice() 函数从数组中移除选定的元素,并用新元素取代它。该函数也将返回包含被移除元素的数组。

提示:如果函数没有移除任何元素(length=0),则将从 start 参数的位置插入被替换数组(参见例子 2)。

注释:不保留被替换数组中的键名。

说明

array_splice() 函数与 array_slice() 函数类似,选择数组中的一系列元素,但不返回,而是删除它们并用其它值代替。

如果提供了第四个参数,则之前选中的那些元素将被第四个参数指定的数组取代。

最后生成的数组将会返回。

语法

array_splice(array,start,length,array)
参数 描述
array 必需。规定数组。
start

必需。数值。规定删除元素的开始位置。

  • 0 = 第一个元素。
  • 如果该值设置为正数,则从数组中该值指定的偏移量开始移除。
  • 如果该值设置为负数,则从数组末端倒数该值指定的偏移量开始移除。
  • -2 means starting from the second last element of the array.
length

Optional. Numeric. Specifies the number of elements to be removed, which is also the length of the returned array.

  • If this value is set to a positive number, then this number of elements are removed.
  • If this value is set to a negative number, then all elements from the start to the end of the array minus the length of the last length are removed.
  • If this value is not set, then all elements from the start parameter set position to the end of the array are removed.
array

Optional. Specifies an array with the elements to be inserted into the original array.

If only one element is present, it can be set as a string without setting it as an array.

Technical Details

Return Value: Returns an array composed of the extracted elements.
PHP Version: 4+

More Examples

Example 1

Similar to the example in the previous part of this page, but the output returns the 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));
?>

Run Instance

Example 2

Set the length parameter to 0:

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

Run Instance