首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

array_splice

(PHP 4, PHP 5, PHP 7)

array_splice - 删除数组的一部分并用其他东西替换它

描述

代码语言:javascript
复制
array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )

从输入数组中删除由offset和length指定的元素,并用替换数组的元素(如果提供)替换它们。

请注意,数字键input不会被保留。

注意:如果replacement不是数组,它将被转换为一个(如(array) $replacement)。 这可能会导致在使用对象或NULL替换时出现意外的行为。

参数

input

输入数组。

offset

如果偏移量为正数,那么被移除部分的开始位置就是从输入数组开始处的偏移量。 如果偏移量是负数,那么它会从输入数组的末尾开始。

length

如果省略长度,则删除从偏移量到数组末尾的所有内容。 如果长度被指定并且是正数,那么许多元素将被删除。 如果长度被指定并且是负数,那么被移除部分的末端将是数组末尾的许多元素。 如果指定了长度并且为零,则不会删除任何元素。 提示:如果还指定了替换,则要从偏移量到数组末尾删除所有内容,请使用count($ input)作为长度。

replacement

如果replacement指定了数组,则删除的元素将被此数组中的元素替换。

如果偏移量和长度都不会被删除,则替换数组中的元素将插入到由偏移量指定的位置。 请注意,替换数组中的键不会被保留。

如果replacement只是一个元素,则不需要在其周围放置array(),除非该元素是一个数组本身,一个对象或NULL

返回值

返回由提取的元素组成的数组。

例子

示例#1 array_splice()示例

代码语言:javascript
复制
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

示例#2 array_splice()示例

以下语句以相同方式更改$输入的值:

代码语言:javascript
复制
<?php

// append two elements to $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));

// remove the last element of $input
array_pop($input);
array_splice($input, -1);

// remove the first element of $input
array_shift($input);
array_splice($input, 0, 1);

// insert an element at the start of $input
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));

// replace the value in $input at index $x
$input[$x] = $y; // for arrays where key equals offset
array_splice($input, $x, 1, $y);

?>

扩展内容

  • array_slice() - 提取数组的一部分
  • unset() - 取消设置给定的变量
  • array_merge() - 合并一个或多个数组

← array_slice

array_sum →

扫码关注腾讯云开发者

领取腾讯云代金券