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)