PHP array_splice () join array usage example

Source: Internet
Author: User

In PHP, an array is joined. a ready-made function can be used, that is, the array_splice () function, which deletes all elements in the array from offset to offset + length, return the deleted elements in the form of arrays. The syntax format of array_splice () is:

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

When offset is a positive value, the join starts from the offset position starting from the array. When offset is a negative value, the join starts from the offset position at the end of the array. If the optional length parameter is ignored, all elements from the offset position to the end of the array will be deleted. If length is given and it is a positive value, the join ends at the offset + leng th position starting with the array. Conversely, if length is given and it is a negative value, the combination ends at the position of count (input_array)-length starting with the array.

Let's take a look at the example of a standard join array. 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 an array to replace the target part. See the following example:

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?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.