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:

  1. The input array / original array
  2. The length of the new array (how many dimensions to create)
  3. A boolean to preserve the original keys or not

array_chunk(array $array, int $length, bool $preserve_keys=false ):array

An example of dividing an array into chunks

Let’s take an initial starter array with 5 values

$input_array = array('a', 'b', 'c', 'd', 'e');
Code language: PHP (php)

If we said we would like to create 2 chunks:

$new_array = array_chunk($input_array, 2); print_r($new_array); /* Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e ) ) */
Code language: PHP (php)

So now let’s try it with preserving the keys:

$new_array = array_chunk($input_array, 2, true); print_r($new_array); /* Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [2] => c [3] => d ) [2] => Array ( [4] => e ) ) */
Code language: PHP (php)

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:

$values = range(1, 31); $rows = array_chunk($values, 7); print "<table>\n"; foreach ($rows as $row) { print "<tr>\n"; foreach ($row as $value) { print "<td>" . $value . "</td>\n"; } print "</tr>\n"; } print "</table>\n";
Code language: PHP (php)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments