I want a function that will return last/first N element of an array.
For example:
$data = array( '0','1','2','3','4','5','6','7','8','9','10' );
If
getItems( $data, '5', 'first' );
output: array( '0','1','2','3','4' )
If
getItems( $data, '2', 'last' );
output: array( '9','10' );
if
getItems( $data, '11', 'first' ); or getItems( $data, '11', 'last' );
output: array( '0','1','2','3','4','5','6','7','8','9','10' );
Is there already a function like this. If not then what is the shortest way.
Thanks
You're looking for array_slice()
(man page here).
Example:
$arr = array(1, 2, 3, 4, 5);
$slice1 = array_slice($arr, 2); //take all elements from 3rd on
$slice2 = array_slice($arr, 0, 3); //take first three elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With