How to Divide an Array into Chunks in PHP
If you have a single-dimensional array, and want to break it into chunks, you can use the array_chunks
method.
It takes 3 arguments:
- The input array / original array
- The length of the new array (how many dimensions to create)
- A boolean to preserve the original keys or not
<strong>array_chunk</strong>(array $array, int $length, bool $preserve_keys=<strong>false</strong> ):array
An example of dividing an array into chunks
Let’s take an initial starter array with 5 values
|
|
If we said we would like to create 2 chunks:
So now let’s try it with preserving the keys:
But where would I use this?
This is particularly helpful when constructing tables into HTML renders, or when needing to populate rows and columns when using Bootstrap css col-x-x
blocks: