Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

Cleaner way to move filtered items in collection

I want to move filtered items but i'm not comfortable with my codes:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$evenNumbers = $collection->filter(fn($item) => $item % 2 == 0);

$oddNumbers = $collection->filter(fn($item) => $item % 2 != 0);

$arrangedItems = $evenNumbers->merge($oddNumbers);

dd($arrangedItems);

result:

 [
     2,
     4,
     6,
     8,
     10,
     1,
     3,
     5,
     7,
     9
 ]

I want to move even numbers to the top of list and vice versa for odd numbers, I did that but i think we can do better with colletion right ? any one has better idea ?

0 likes
5 replies
MichalOravec's avatar
Level 75
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$result = $collection->groupBy(fn($item) => $item % 2)->reverse()->flatten();
bugsysha's avatar

@untymage what @michaloravec wrote is not correct. If you have an array that is not ordered it will break.

$collection = collect([2, 4, 6, 8, 10, 1, 3, 5, 7, 9]);

$result = $collection->groupBy(fn ($item) => $item % 2 )->reverse()->flatten(); // 1,3,5,7,9,2,4,6,8,10

You need sort function:

$result = collect([2, 4, 6, 8, 10, 1, 3, 5, 7, 9])->sort(function ($a, $b) {
    if ($a % 2 === 0 && $b % 2 ===0) return $a > $b;
    if ($a % 2 !== 0 && $b % 2 !==0) return $a > $b;
    return $a < $b;
});

This way you will always have correct order.

Or you would have to add sort() to his solution.

$result = $collection->sort()->groupBy(fn($item) => $item % 2)->reverse()->flatten();
1 like

Please or to participate in this conversation.