Array_slice () of the sequence of PHP array functions-take a value out of the array according to the condition and return the _php tip

Source: Internet
Author: User
array_slice () Definition and usage

The Array_slice () function extracts a value from the array, and returns it.

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

Grammar
Array_slice (array,offset,length,preserve) parameter description
Array required. A specified array of inputs.
Offset required. Numerical. Specify the starting position of the element to be removed.

In the case of a positive number, start from the back and, if it is negative, take the absolute value of the offset forward.

Length is optional. Numerical. Specify the length of the array to be returned.

If it is a negative number, then forward, select the element of the value in absolute numbers. If this value is not set, all elements are returned.

Preserve optional. Possible values:

True-Preserve keys
False-Default-reset key

Example 1
Copy Code code 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
With a negative offset parameter:
Copy Code code 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
The preserve parameter is set to true:
Copy Code code 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
With string key:
Copy Code code 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.