当前位置:编程学习 > > 正文

php如何将数组清空(PHP实现数组向任意位置插入,删除,替换数据操作示例)

时间:2022-03-30 00:43:06类别:编程学习

php如何将数组清空

PHP实现数组向任意位置插入,删除,替换数据操作示例

本文实例讲述了PHP实现数组向任意位置插入,删除,替换数据操作。分享给大家供大家参考,具体如下:

array_splice函数可以实现任意位置插入和删除,替换

array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )

offset 如果 offset 为正,则从 input 数组中该值指定的偏移量开始移除。如果 offset 为负,则从 input 末尾倒数该值指定的偏移量开始移除。
length 如果省略 length,则移除数组中从 offset 到结尾的所有部分。如果指定了 length 并且为正值,则移除这么多单元。如果指定了 length 并且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的单元。 如果设置了 length 为零,不会移除单元。 小窍门:当给出了 replacement 时要移除从 offset 到数组末尾所有单元时,用 count($input) 作为 length。
replacement 如果给出了 replacement 数组,则被移除的单元被此数组中的单元替代。

如果 offset 和 length 的组合结果是不会移除任何值,则 replacement 数组中的单元将被插入到 offset 指定的位置。 注意替换数组中的键名不保留。

如果用来替换 replacement 只有一个单元,那么不需要给它加上 array(),除非该单元本身就是一个数组、一个对象或者 NULL。

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • <?php
  • $input = array("red", "green", "blue", "yellow");
  • $x = "black";
  • $y = "purple";
  • // 添加两个新元素到 $input
  • array_push($input, $x, $y);
  • array_splice($input, count($input), 0, array($x, $y));
  • // 移除 $input 中的最后一个元素
  • array_pop($input);
  • array_splice($input, -1);
  • // 移除 $input 中第一个元素
  • array_shift($input);
  • array_splice($input, 0, 1);
  • // 在 $input 的开头插入一个元素
  • array_unshift($input, $x, $y);
  • array_splice($input, 0, 0, array($x, $y));
  • // 在 $input 的索引 $x 处替换值
  • $input[$x] = $y; // 对于键名和偏移量等值的数组
  • array_splice($input, $x, 1, $y);
  • 希望本文所述对大家PHP程序设计有所帮助。

    原文链接:https://blog.csdn.net/z15818264727/article/details/81252513

    上一篇下一篇

    猜您喜欢

    热门推荐