Re: [RFC] array_partition()
| From: | Ayoub EZZINI | Date: | Mon, 26 Oct 2026 14:34:14 +0000 |
| Subject: | Re: [RFC] array_partition() | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-132931@lists.php.net to get a copy of this message | ||
Hi mickmackusa,
> Instead of potentially creating array_partition() and eventually
> array_group(), I feel any benefits of array_partition() should be baked
> into an array_group() function for greater utility in a unified function.
Thanks for thinking it through. Seeded keys would indeed solve the
missing-bucket problem, and with string labels the result reads well:
['adults' => $adults, 'minors' => $minors] = array_group(
$users,
fn($u) => $u->age >= 18 ? 'adults' : 'minors',
['adults', 'minors'],
);
I still think the two-way split deserves its own function, for three
reasons:
1. Destructuring is by key, not by order. With a boolean callback, the
keys become 1 and 0 whatever order they are seeded in, so
[$adults, $minors] = array_group($users, $predicate, [true, false])
puts the minors in $adults. You have to switch to labels, as above.
2. With labels, the callback, the seed list and the destructuring keys
have to agree. A typo ('adult' vs 'adults') silently creates a third
group and leaves one variable empty. array_partition() only needs a
predicate, and its result shape is fixed.
3. PHP already pairs general functions with simpler, specialised ones
for common cases: array_filter() with array_find() and array_any().
A two-way split is common enough to warrant the same treatment.
It doesn't rule out a future array_group(), which raises its own
design questions (return shape, unknown keys, key preservation).
I'll add the seeded-keys alternative to the RFC's "Why not a general
grouping function?" section.
Thanks,
Ayoub
On Mon, Oct 26, 2026 at 12:26 PM mickmackusa <mickmackusa@gmail.com> wrote:
>
> I wouldn't be disappointed to see array_partition() added to the language, but the longer
> I think about it, a well-designed
array_group() function could
> provide the equivalent behavior as well as afford other than just 2 static groups.
>
> It seems like the only relevant difference is the fact that array_partition() always returns an
> indexed array of two arrays without needing to push 2 empty arrays for padding. Theoretically,
> array_group() might not return any subarrays when there are no qualifying items to retain. Does
> array_group() need an optional 3rd parameter which declares an empty array for each nominated
> grouping key which can be nominated in a particular order? Food for thought.
>
> Instead of potentially creating array_partition() and eventually array_group(), I feel any
> benefits of array_partition() should be baked into an array_group() function for greater utility in
> a unified function.
>
> mickmackusa