DEV Community

Reza Rabbani
Reza Rabbani

Posted on

Chunk multidimensional array by value in Laravel

Have you ever needed to put arrays with same value together? It's super easy using collections in Laravel!

Just imagine you have the following array:

$people = [
    ['name' => 'Alex', 'age' => 25],
    ['name' => 'Martin', 'age' => 32],
    ['name' => 'John', 'age' => 25]
];
Enter fullscreen mode Exit fullscreen mode

And want to put people with same age into same groups. Using collection in Laravel you can do it in one line:

$chunkedByAge = collect($people)->chunkWhile(fn($v, $k, $c) => $v['age'] == $c->last()['age']);
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Top comments (0)