harunB10
harunB10

Reputation: 5207

How to sort array and take 5 items only?

How to get only 5 newest articles from array?

For example:

  usort($articles, function ($item1, $item2) {
        return $item2['created_at'] <=> $item1['created_at'];
    });

This will sort them descending and I don't need to show all of them.

What would be the best way to do this? Is it possible without looping again and storing in new array?

Upvotes: 1

Views: 47

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

Using array_slice on the sorted array should do.

usort($articles, function ($item1, $item2) {
    return $item2['created_at'] <=> $item1['created_at'];
});

$fiveFirst = array_slice($articles, 0, 5);

Upvotes: 3

Related Questions