Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Add `countBy` method to Collection #27770

Merged
merged 3 commits into from Mar 5, 2019

Conversation

Projects
None yet
5 participants
@jamierumbelow
Copy link
Contributor

jamierumbelow commented Mar 4, 2019

Adds a countBy method to Illuminate\Support\Collection.

By default, this method counts each appearance of a given value:

collect([ 1, 2, 2, 2, 3 ])->countBy(); // == collect([ 1 => 1, 2 => 3, 3 => 1 ])

It also accepts a predicate:

collect([ 1, 2, 2, 3, 4 ])->countBy(function ($i) {
    return $i % 2 === 0;
}); // == collect([ true => 3, false => 2 ])

collect([ 'alice@gmail.com', 'bob@yahoo.fr', 'carlos@gmail.com' ])
    ->countBy(function ($email) {
        return substr(strrchr($email, "@"), 1);
    }); // == collect([ 'gmail.com' => 2, 'yahoo.fr' => 1 ])

@driesvints driesvints changed the title Add `countBy` method to Collection [5.8] Add `countBy` method to Collection Mar 4, 2019

@driesvints
Copy link
Member

driesvints left a comment

Please fix the StyleCI warnings.

public function countBy($predicate = null)
{
if (is_null($predicate)) {
$predicate = function ($val, $key) {

This comment has been minimized.

@BrandonSurowiec

BrandonSurowiec Mar 4, 2019

Contributor
Suggested change
$predicate = function ($val, $key) {
$predicate = function ($val) {

You aren't utilizing the $key so it doesn't need to be set.

jamierumbelow added some commits Mar 5, 2019

StyleCI warnings fixed.

@taylorotwell taylorotwell merged commit 563af72 into laravel:5.8 Mar 5, 2019

1 check passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details

@jamierumbelow jamierumbelow deleted the jamierumbelow:add_collection_tally branch Mar 5, 2019

@vlakoff

This comment has been minimized.

Copy link
Contributor

vlakoff commented Mar 11, 2019

For the "without predicate" mode, couldn't we use array_count_values()? Probably much, much faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.