Hi internals,
I'd like to request RFC karma on the wiki to propose a new function,
array_partition(). My wiki username is: ayoubezzini
The function splits an array into the elements that satisfy a callback
and those that don't, in a single pass:
[$adults, $minors] = array_partition($users, fn($u) => $u->age >= 18);
It returns [$matching, $nonMatching], preserves keys, and takes the same
$mode argument (ARRAY_FILTER_USE_KEY / ARRAY_FILTER_USE_BOTH) as
array_filter(). Today the same result needs two array_filter() passes
with a negated callback, or array_filter() followed by array_diff_key().
The same operation exists as Laravel's Collection::partition(), Ruby's
Enumerable#partition, Kotlin's partition and Rust's Iterator::partition.
An implementation with tests is available as a draft PR:
https://github.com/php/php-src/pull/24568
I'll open the formal [RFC] discussion thread once the wiki page is up.
Thanks,
Ayoub Ezzini
Hi Ayoub,
I am in support of array_partition() being added to the language in some
way. Here is my feedback:
- Semantically, the function name affords an indefinite number of
groups/partitions. I have had many use cases where more than two partitions
are desired. - It feels unintuitive that
truecallback outcomes map to the0key and
falseoutcomes map to1. - I want to be able to make unlimited groups keyed by the callback's return
value (so long as the return value is a string or an int).
$ageGrouped = array_partition($users, fn($u) => $u->age ?? -1);
$byFirstByte = array_partition($words, fn($word) => substr($word, 0, 1)); - The callback should have access to the arrays keys and values.
$modulusGrouped = array_partition($rows, fn($row, $i) => $i % 7); - Allowing your original intention of an indexed array with true outcomes
first is still afforded by tweaking the evaluation or merely negating the
boolean outcomes with!(expression). - Was strictly partitioning into only two parts a deliberate intention
specific to the the term "partition"? I mean, did you deliberately choose
to not name the functionarray_group()/array_batch()which might align
with my behavioral deviation?
Good luck with the RFC.
mickmackusa
Hi,
Thanks for the support and the detailed feedback!
- Semantically, the function name affords an indefinite number of
groups/partitions.
[...]- Was strictly partitioning into only two parts a deliberate intention
specific to the term "partition"?
Yes, it was deliberate. In the languages and libraries PHP developers
are most likely to know, "partition" means a split by a boolean
predicate into exactly two parts: Ruby's Enumerable#partition, Kotlin's
partition, Rust's Iterator::partition, Haskell's Data.List.partition and
Laravel's Collection::partition. Each of them also ships grouping as a
separate function (group_by, groupBy, ...). I'd like PHP to follow the
same split, so that array_partition() does what people coming from
those ecosystems expect.
- I want to be able to make unlimited groups keyed by the callback's
return value
That's a useful function too, but I think it's a different one. There
is an existing draft RFC for exactly that, array_group() by Boro
Sitnikovski (https://wiki.php.net/rfc/array_group, 2023), which never
went to a vote. I'd be happy to see it revived, and the two would
complement each other.
Using a general grouping function for the two-way case is also less
convenient: the bucket keys come from the callback's return value, and
a bucket is missing entirely when nothing falls into it. You'd write:
$groups = array_group($users, fn($u) => $u->age >= 18 ? 'adult' : 'minor');
$adults = $groups['adult'] ?? [];
$minors = $groups['minor'] ?? [];
whereas array_partition() always returns both parts, so destructuring
always works:
[$adults, $minors] = array_partition($users, fn($u) => $u->age >= 18);
- It feels unintuitive that
truecallback outcomes map to the0key
andfalseoutcomes map to1.
The result is meant to be read as a pair rather than a map from boolean
to bucket, and "matching first" is the order used by all of the
functions above. With destructuring, the names carry the meaning:
[$matching, $rest].
- The callback should have access to the arrays keys and values.
Agreed, and this is already done: following review on the PR, the
callback now receives ($value, $key), like array_find() and friends,
and the $mode parameter is gone:
function array_partition(array $array, callable $callback): array
https://github.com/php/php-src/pull/24568
I'll cover the naming and the relationship to array_group() in the RFC.
Thanks,
Ayoub
Hi Ayoub,
I am in support of
array_partition()being added to the language in some way. Here is my feedback:
- Semantically, the function name affords an indefinite number of groups/partitions. I have had many use cases where more than two partitions are desired.
- It feels unintuitive that
truecallback outcomes map to the0key andfalseoutcomes map to1.- I want to be able to make unlimited groups keyed by the callback's return value (so long as the return value is a string or an int).
$ageGrouped = array_partition($users, fn($u) => $u->age ?? -1);
$byFirstByte = array_partition($words, fn($word) => substr($word, 0, 1));- The callback should have access to the arrays keys and values.
$modulusGrouped = array_partition($rows, fn($row, $i) => $i % 7);- Allowing your original intention of an indexed array with true outcomes first is still afforded by tweaking the evaluation or merely negating the boolean outcomes with
!(expression).- Was strictly partitioning into only two parts a deliberate intention specific to the the term "partition"? I mean, did you deliberately choose to not name the function
array_group()/array_batch()which might align with my behavioral deviation?Good luck with the RFC.
mickmackusa
Hi Ayoub,
- It feels unintuitive that
truecallback outcomes map to the0key
andfalseoutcomes map to1.
I'm also in support, and this would have been my only observation: my
partition functions also map passes and rejects to true and false
respectively (so the result is a mapping from booleans to array values).
If that mapping were retained, it could be documented in code as
[true => $passed, false => $rejected] = array_partition(...);
or
$adult_tested = array_partition(...);
$adults = $adult_tested[true];
$minors = $adult_tested[false];
I would also prefer the callback parameter to be named $predicate, to
emphasise that it is supposed to return a boolean. $callback doesn't
convey as much about what it's for - the same name is used, for example,
in usort(), where it's a comparator. It didn't matter until named
parameters became a thing.
Hi Morgan,
Thanks for the support!
my partition functions also map passes and rejects to true and false
respectively (so the result is a mapping from booleans to array values).[true => $passed, false => $rejected] = array_partition(...);
I looked at this, and the catch is that boolean array keys are cast to
integers, so true => 1 and false => 0. A boolean-keyed result would
therefore have to put the rejected elements at index 0, and then
positional destructuring silently gives the opposite of what it reads:
[$adults, $minors] = array_partition($users, fn($u) => $u->age >= 18);
// with a bool-keyed result, $adults would hold the minors
Whichever layout is chosen, one of the two idioms ends up swapped. I'd
rather keep "matching first" at index 0, since that's what Ruby, Kotlin,
Rust, Haskell and Laravel all return, and it makes the plain
[$matching, $rest] destructuring work. I'll document the pitfall
explicitly in the RFC, with your example, so nobody reaches for
[true => ..., false => ...] expecting it to work.
I would also prefer the callback parameter to be named $predicate, to
emphasise that it is supposed to return a boolean.
I agree it's more descriptive in isolation. But every other array
function taking a callback names it $callback, including array_filter()
and the recent array_find(), array_find_key(), array_any() and
array_all(), which are also predicates. With named arguments I think
it's more valuable that callback: works the same way across the whole
family, so I'd prefer to keep $callback for consistency. I'll mention
it in the RFC as a considered alternative.
Thanks,
Ayoub
Hi Ayoub,
- It feels unintuitive that
truecallback outcomes map to the0key
andfalseoutcomes map to1.
I'm also in support, and this would have been my only observation: my
partition functions also map passes and rejects to true and false
respectively (so the result is a mapping from booleans to array values).If that mapping were retained, it could be documented in code as
[true => $passed, false => $rejected] = array_partition(...);
or
$adult_tested = array_partition(...);
$adults = $adult_tested[true];
$minors = $adult_tested[false];I would also prefer the callback parameter to be named $predicate, to
emphasise that it is supposed to return a boolean. $callback doesn't
convey as much about what it's for - the same name is used, for example,
inusort(), where it's a comparator. It didn't matter until named
parameters became a thing.
Hi Ayoub
I'd like to request RFC karma on the wiki to propose a new function,
array_partition(). My wiki username is: ayoubezzini
RFC karma was granted, good luck!
Ilija