首页 > 编程 > PHP > 正文

PHP编程讲解array_splice函数

2020-03-22 17:25:44
字体:
来源:转载
供稿:网友
  • array_splice — 把数组中的一部分去掉并用其它值取代

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

    说明


    array array_splice ( array &input, int offset [, int length [, array replacement]] )

    input 必需。规定数组。 offset 必需。数值。如果 offset 为正,则从输入数组中该值指定的偏移量开始移除。如果 offset 为负,则从输入数组末尾倒数该值指定的偏移量开始移除。 length 可选。数值。如果省略该参数,则移除数组中从 offset 到 结尾的所有部分。如果指定了 length 并且为正值,则移除这么多元素。如果指定了 length 且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的元素。 replacement 被移除的元素由此数组中的元素替代。如果没有移除任何值,则此数组中的元素将插入到指定位置。
    参数 描述

    提示:如果函数没有删除任何元素 (length=0),则替代数组将从 start 参数的位置插入。

    注释:不保留替代数组中的键。

    以下表达式以同样方式修改了 $input:

    表 1. array_splice() 等价表达式


    array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y)) //array_push函数array_pop($input) array_splice($input, -1)//array_pop函数array_shift($input) array_splice($input, 0, 1)    //array_shift函数array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y)) $input[$x] = $y // 对于键名和偏移量等值的数组 array_splice($input, $x, 1, $y)返回一个包含被移除单元的数组。

    例 1. array_splice() 例子

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

    PHP编程

    郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表