PHP to insert, delete and replace arrays to any location

Time:2020-4-4

The example of this paper describes how to insert, delete and replace data in any place in PHP. To share with you for your reference, as follows:

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 If offset is positive, it is removed from the input array at the offset specified by the value. If the offset is negative, it is removed from the end of input by counting down the offset specified by the value.
length If length is omitted, all parts of the array from offset to the end are removed. If length is specified and is a positive value, remove so many cells. If length is specified and is negative, all cells from offset to the last reciprocal length of the array are removed. If length is set to zero, cells are not removed. Tip: when a replacement is given to remove all cells from offset to the end of the array, count ($input) is used as the length.
replacement If a replacement array is given, the removed cells are replaced by the cells in the array.

If the combination of offset and length does not remove any values, the cells in the replacement array are inserted at the location specified by offset. Note that the key names in the replacement array are not reserved.

If there is only one cell to replace a replacement, you do not 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 $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
//Remove the last element in $input
array_pop($input);
array_splice($input, -1);
//Remove the first element in $input
array_shift($input);
array_splice($input, 0, 1);
//Insert an element at the beginning of $input
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
//Replace value at index $X of $input
$input [$x] = $Y; // for arrays with key names and offset equivalents
array_splice($input, $x, 1, $y);

For more information about PHP, readers interested in PHP can see our special topics: PHP array operation skills, PHP string usage summary, PHP common functions and skills summary, PHP error and exception handling methods summary, PHP basic grammar tutorial, PHP object-oriented programming tutorial, PHP + MySQL database operation Introductory course and PHP common database operation skills summary

I hope this article is helpful for PHP programming.