Php Array Function Sequence-array_slice ()-extracts a value from the Array Based on the Conditions and returns

Source: Internet
Author: User

Array_slice () Definition and usage

The array_slice () function extracts a value from the Array Based on the Conditions and returns it.

Note: If the array has a string key, the returned array retains the key name. (See example 4)

Syntax
Array_slice (array, offset, length, preserve) parameter description
Array is required. Specifies the input array.
Offset is required. Value. Specifies the start position of the retrieved element.

If it is a positive number, it is taken from the beginning to the end. If it is a negative value, it is taken from the back to the absolute value of the offset.

Length is optional. Value. Specifies the length of the returned array.

If it is a negative number, select the element of the absolute value from the back to the front. If this value is not set, all elements are returned.

Preserve is optional. Possible values:

True-reserved key
False-default-Reset key

Example 1
Copy codeThe Code is as follows:
<? Php
$ A = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
Print_r (array_slice ($ a, 1, 2 ));
?>

Output:

Array ([0] => Cat [1] => Horse) Example 2
Offset parameter with negative values:
Copy codeThe Code is as follows:
<? Php
$ A = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
Print_r (array_slice ($ a,-2, 1 ));
?>

Output:

Array ([0] => Horse) Example 3
Set the preserve parameter to true:
Copy codeThe Code is as follows:
<? Php
$ A = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
Print_r (array_slice ($ a, 1, 2, true ));
?>

Output:

Array ([1] => Cat [2] => Horse) Example 4
String key:
Copy codeThe Code is as follows:
<? Php
$ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ", "d" => "Bird ");
Print_r (array_slice ($ a, 1, 2 ));
?>

Output:

Array ([B] => Cat [c] => Horse)

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.