Skip to content

[12.x] Feature: Array partition#54859

Merged
taylorotwell merged 5 commits into
laravel:12.xfrom
liamduckett:feature/array-partition
Mar 4, 2025
Merged

[12.x] Feature: Array partition#54859
taylorotwell merged 5 commits into
laravel:12.xfrom
liamduckett:feature/array-partition

Conversation

@liamduckett

Copy link
Copy Markdown
Contributor

Hey, this PR adds a partition method to the Array helper.

This allows using the existing partition logic, without needing to reach for collections.

// Pre code:
$numbers = [0, 1, 2, 3, 4, 5];

// Before:
[$evens, $odds] = collect($numbers)->partition(fn(int $number) => $number % 2 === 0);

// After:
[$evens, $odds] = Arr::partition($numbers, fn(int $number) => $number % 2 === 0);

I also converted the existing Collection::partition to use the Arr::partition method, to prevent duplication. Happy to revert this bit if preferable.

@crynobone crynobone changed the title Feature: Array partition [12.x] Feature: Array partition Mar 4, 2025
$failed = [];

foreach ($array as $key => $item) {
if ($callback($item, $key)) {

@pandiselvamm pandiselvamm Mar 4, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion:

foreach ($array as $key => $item) {
        ($callback($item, $key) ? $passed : $failed)[$key] = $item;
}

@taylorotwell

Copy link
Copy Markdown
Member

@liamduckett do you mind sending some docs over for this?

@liamduckett

Copy link
Copy Markdown
Contributor Author

Thanks @pandiselvamm. Speedy!

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.

3 participants