Dataflashsabot
Dataflashsabot

Reputation: 1509

How to get the last n items in a PHP array as another array?

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

Upvotes: 53

Views: 29876

Answers (2)

joseantgv
joseantgv

Reputation: 2023

You can use array_slice:

$arr = array_slice($old_arr, -$n, $n, true);

If the array indices are meaningful to you, remember that array_slice will reset the numeric array indices while keeping the original order. You need the preserve_keys flag (4th parameter) set to true to avoid this.

Upvotes: 17

user142162
user142162

Reputation:

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

$arr = array_slice($old_arr, -$n);

Upvotes: 106

Related Questions