PHP array_slice () function
PHP Array functions
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
Element.
Preserve is optional. Possible values:
True-reserved key
False-default-reset key
<? Php
/*
Example in manual
*/
$ Input = array ("a", "B", "c", "d", "e ");
$ Output = array_slice ($ input, 2); // returns "c", "d", and "e ",
$ Output = array_slice ($ input, 2,-1); // returns "c", "d"
$ Output = array_slice ($ input,-2, 1); // returns "d"
$ Output = array_slice ($ input, 0, 3); // returns "a", "B", and "c"
?>
Instance
<? Php
$ Term = $ _ REQUEST ['Q'];
$ Images = array_slice (scandir ("images"), 2 );
Foreach ($ images as $ value ){
If (strpos (strtolower ($ value), $ term) === 0 ){
Echo $ value ."";
}
}
?>
<? Php
// Split the given array into n number of pieces
Function array_split ($ array, $ pieces = 2)
{
If ($ pieces <2)
Return array ($ array );
$ NewCount = ceil (count ($ array)/$ pieces );
$ A = array_slice ($ array, 0, $ newCount );
$ B = array_split (array_slice ($ array, $ newCount), $ pieces-1 );
Return array_merge (array ($ a), $ B );
}
// Examples:
$ A = array );
Array_split ($ a, 2); // array (1, 2, 3, 4, 5), array (6, 7, 8, 9, 10 ))
Array_split ($ a, 3); // array (1, 2, 3, 4), array (5, 6, 7), array
(8, 9, 10 ))
Array_split ($ a, 4); // array (1, 2, 3), array (4, 5, 6), array (7, 8 ),
Array (9, 10 ))
?>