PHP Implementation Array to any position insert delete replace data operation example

  • 2021-12-04 18:25:54
  • OfStack

This article example describes the implementation of PHP array to any position to insert, delete, replace data operations. Share it for your reference, as follows:

The array_splice function can be used to insert, delete and replace any position

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 数组,则被移除的单元被此数组中的单元替代。

If the combination of offset and length results in no value being removed, the cells in the replacement array are inserted into the positions specified by offset. Note that the key names in the replacement array are not preserved.

If there is only one cell to replace replacement, there is no need to add array () to it unless the cell itself is an array, an object, or NULL.


<?php
$input = array("red", "green", "blue", "yellow");
$x = "black";
$y = "purple";
//  Add two new elements to the  $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
//  Remove  $input  The last of the 1 Elements 
array_pop($input);
array_splice($input, -1);
//  Remove  $input  Middle grade 1 Elements 
array_shift($input);
array_splice($input, 0, 1);
//  In  $input  Insert at the beginning of 1 Elements 
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
//  In  $input  Index of  $x  Replace value at 
$input[$x] = $y; //  For an array of key names and offset equivalents 
array_splice($input, $x, 1, $y);

For more readers interested in PHP related content, please check the topics on this site: "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "php Common Functions and Skills Summary", "PHP Error and Exception Handling Methods Summary", "PHP Basic Syntax Introduction Course", "php Object-Oriented Programming Introduction Course", "php+mysql Database Operation Introduction Course" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: