The โ countBy method in collections is a powerful way to count the occurrences of values in a collection. You can pass a callback to specify how you want the elements to be counted.
use Illuminate\Support\Collection;
$users = collect([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 20],
['name' => 'Charlie', 'age' => 30],
['name' => 'David', 'age' => 25],
]);
$ageCounts = $users->countBy(function ($user) {
return $user['age'];
});
$ageCounts->all();
// [30 => 2, 20 => 1, 25 => 1]
|