Reputation: 5207
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
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