DEV Community

Reza Rabbani
Reza Rabbani

Posted on

1 1

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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more