目录

PHP array_splice() 函数

❮ PHP 数组参考

示例

从数组中删除元素并用新元素替换它:

<?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);
?>
亲自试一试 »

定义和用法

array_splice() 函数从数组中删除选定的元素并用新元素替换。该函数还返回一个包含已删除元素的数组。

提示:如果函数不删除任何元素(长度=0),则替换的数组将从起始参数的位置插入(参见示例 2)。

笔记:替换数组中的键不会保留。


语法

array_splice( array, start, length, array)

参数值

Parameter Description
array Required. Specifies an array
start Required. 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.
length Optional. 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.
array Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array.


技术细节

返回值: 返回由提取的元素组成的数组
PHP 版本: 4+

更多示例

示例1

与页面顶部的示例相同的示例,但输出是返回的数组:

<?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));
?>
亲自试一试 »

示例2

将长度参数设置为 0 时:

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

❮ PHP 数组参考