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
2010-08-28 18:11:17
Thank you! I just couldn't find that function.
Dataflashsabot
2010-08-28 18:14:16
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
2010-08-28 18:11:51
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
2010-08-28 18:16:06