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)