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

jamierumbelow
Copy link
Contributor

@jamierumbelow 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
Copy link
Member

@driesvints driesvints left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please fix the StyleCI warnings.

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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

@driesvints driesvints dismissed their stale review March 5, 2019 10:52

StyleCI warnings fixed.

@taylorotwell taylorotwell merged commit 563af72 into laravel:5.8 Mar 5, 2019
@jamierumbelow jamierumbelow deleted the add_collection_tally branch March 5, 2019 13:39
@vlakoff
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
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants