The partition method in the Collection class allows you to directly destructure the result into two separate collections. This enables immediate handling of elements that satisfy a condition and those that do not, without needing additional filtering.
$collection = collect([10, 20, 30, 40, 50, 60]);
// Partition the collection into two parts: numbers less than 35 and those 35 or above
[$lessThanThirtyFive, $thirtyFiveOrMore] = $collection->partition(fn($number) => $number < 35);
$lessThanThirtyFive->all(); // [10, 20, 30]
$thirtyFiveOrMore->all(); // [40, 50, 60]
|