tags:

views:

40

answers:

2

How to I get an array of the last n items of another array in PHP?

+6  A: 

$n is equal to the number of items you want off the end.

$arr = array_slice($old_arr, -$n);
Tim Cooper
Thank you! I just couldn't find that function.
Dataflashsabot
A: 

You can use http://us2.php.net/array_slice.

$new = array_slice($old, $n);

However, $n is the offset to start the slice, so to calculate it, you would need to subtract this from the length of the array: $n = count($old) - $target_size.

efritz
Or read the documentation you linked and realize that negative offsets start at the end of the array. `If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.`
Femaref