I want a function that will return last/first N element of an array.
For example:
$data = array( \'0\',\'1\',\'2\',\'3\',\'4\',\'5\'
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);
}
}
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