Returning first x items from array


Question

I want to return first 5 items from array. How can I do this?

1
126
10/15/2009 10:14:15 AM

Accepted Answer

array_slice returns a slice of an array

$sliced_array = array_slice($array, 0, 5)

is the code you want in your case to return the first five elements

254
1/20/2015 6:20:00 AM

array_splice — Remove a portion of the array and replace it with something else:

$input = array(1, 2, 3, 4, 5, 6);
array_splice($input, 5); // $input is now array(1, 2, 3, 4, 5)

From PHP manual:

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement]])

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length .


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon