PHP: any function that returns the first / last N elements of an array

I need a function that will return the last / first element of an N array.

For instance:

$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' ); 

Does such a function already exist. If not, what is the shortest way.

thanks

+4
source share
2 answers

You are 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 
+9
source
 function getItems($data, $length, $startLocation){ if($startLocation == 'first'){ return array_slice($data, 0, $length); }else if($startLocation == 'last'){ $offset = count($data) - $length - 1; if($offset < 0) $offset = 0; return array_slice($data, $offset, $length); } } 
+1
source

Source: https://habr.com/ru/post/1332185/


All Articles