从数组中删除元素并用新元素替换它:
<?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+ |
与页面顶部的示例相同的示例,但输出是返回的数组:
<?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));
?>
亲自试一试 »
将长度参数设置为 0 时:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!