PHP array truncation array_slice () function

Source: Internet
Author: User
Define and use the array_slice () function in the PHP array
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)
Parameters
Array
Required. Specifies the input array.
Offset
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
Optional. Value. Specifies the length of the returned array. If the length is positive, the number of elements is returned. If length is negative, the sequence ends so far from the end of the array. If this parameter is omitted, the sequence starts from offset to the end of array.
Preserve
Optional. Possible values:
True-reserved key
False-default-reset key


Example 1
$ 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:
$ 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:
$ 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:
$ 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.