array_chunk in php

To divide an array into smaller, evenly sized arrays, use the array_chunk() function:

$chunks = array_chunk(array, size [, preserve_keys]);

The function returns an array of the smaller arrays. The third argument, pre serve_keys, is a Boolean value that determines whether the elements of the new arrays have the same keys as in the original (useful for associative arrays) or new numeric keys starting from 0 (useful for indexed arrays). The default is to assign new keys, as shown here:

$nums = range(1, 7);
$rows = array_chunk($nums, 3);
print_r($rows);
Array (
 [0] => Array (
 [0] => 1
 [1] => 2
 [2] => 3
 )
 [1] => Array (
 [0] => 4
 [1] => 5
 [2] => 6
 )
 [2] => Array (
 [0] => 7
 )
)

Leave a Comment