Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Any function that return first/last N elements of an array

Tags:

arrays

php

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

like image 430
Awan Avatar asked Dec 28 '22 03:12

Awan


1 Answers

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
like image 145
Rafe Kettler Avatar answered Mar 06 '23 12:03

Rafe Kettler