Home > Backend Development > PHP Tutorial > PHP array_splice() splice array usage example_PHP tutorial

PHP array_splice() splice array usage example_PHP tutorial

WBOY
Release: 2016-07-13 10:30:21
Original
954 people have browsed it

To join arrays in PHP, we have a ready-made function that can be used, that is the array_splice() function, which will delete all elements from the array starting at offset to ending at offset+length, and return it in the form of an array The deleted element. The syntax format of array_splice() is:

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

When offset is a positive value, the joining will start from the offset position from the beginning of the array. When offset is a negative value, the joining will start from the offset position from the end of the array. If the optional length parameter is omitted, all elements starting at offset position and ending at the end of the array will be removed. If length is given and is positive, the join ends at offset + leng th from the beginning of the array. Conversely, if length is given and is negative, the union will end count(input_array)-length from the beginning of the array.

Let’s look at a standard example of joining arrays, PHP code:

 1

 2$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");

 3$subset = array_splice($fruits, 4);

 4print_r($fruits);

 5print_r($subset);

 6//The output result is:

 7// Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )

 8// Array ( [0] => Grape [1] => Lemon [2] => Watermelon )

9?>

We can also use the optional parameter replacement to specify the array to replace the target part. Please see the example below:

 1

 2$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");

 3$subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));

 4print_r($fruits);

 5print_r($subset);

 6// Output result:

 7// Array ( [0] => Apple [1] => Banana [2] => Green Apple [3] => Red Apple [4] => Watermelon )

 8// Array ( [0] => Orange [1] => Pear [2] => Grape [3] => Lemon )

9?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/765440.htmlTechArticleTo join arrays in PHP, we have a ready-made function that can be used, that is the array_splice() function, which will delete All elements in the array starting from offset and ending at offset+length, and ending with...
of the array
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template