Break up an array into smaller arrays with PHP’s array_chunk() function

This little known and arguably terribly named function “array_chunk” is a hidden gem. As a PHP developer, I often find myself dealing with large arrays of customer data or transactions and need to work through the array one by one. The problem with this is that usually you eat up a lot of memory while you step through, as sometimes there’s other arrays you’re building, or producing a filtered version of the main array, or using a temporary array for some reason.

array_chunk() will break up a big array into a (configurable) number array of smaller arrays. It’s great when you’re working on a large array e.g. a CSV import function or something like that.

There’s examples and documentation in the php manual.

Leave a Reply