Skip to content

Commit 6468835

Browse files
authored
[12.x] Feature: Array partition (#54859)
* add array partition method * allow traversable in array partition * use array partition in collection partition * remove unneccesary import * use iterable instead of array|Traversable
1 parent 5645879 commit 6468835

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -942,6 +942,32 @@ public static function reject($array, callable $callback)
942942
return static::where($array, fn ($value, $key) => ! $callback($value, $key));
943943
}
944944

945+
/**
946+
* Partition the array into two arrays using the given callback.
947+
*
948+
* @template TKey of array-key
949+
* @template TValue of mixed
950+
*
951+
* @param iterable<TKey, TValue> $array
952+
* @param callable $callback
953+
* @return array<int<0, 1>, array<TKey, TValue>>
954+
*/
955+
public static function partition($array, callable $callback)
956+
{
957+
$passed = [];
958+
$failed = [];
959+
960+
foreach ($array as $key => $item) {
961+
if ($callback($item, $key)) {
962+
$passed[$key] = $item;
963+
} else {
964+
$failed[$key] = $item;
965+
}
966+
}
967+
968+
return [$passed, $failed];
969+
}
970+
945971
/**
946972
* Filter items where the value is not null.
947973
*

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -504,20 +504,11 @@ public function forPage($page, $perPage)
504504
*/
505505
public function partition($key, $operator = null, $value = null)
506506
{
507-
$passed = [];
508-
$failed = [];
509-
510507
$callback = func_num_args() === 1
511508
? $this->valueRetriever($key)
512509
: $this->operatorForWhere(...func_get_args());
513510

514-
foreach ($this as $key => $item) {
515-
if ($callback($item, $key)) {
516-
$passed[$key] = $item;
517-
} else {
518-
$failed[$key] = $item;
519-
}
520-
}
511+
[$passed, $failed] = Arr::partition($this->getIterator(), $callback);
521512

522513
return new static([new static($passed), new static($failed)]);
523514
}

0 commit comments

Comments
 (0)