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
$input_array = array('a', 'b', 'c', 'd', 'e');
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
)
)
*/
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
)
)
*/
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";