The array_chunk() function splits an array into chunks and stores the chunks into new arrays.
PHP array_chunk() function has the following syntax.
array_chunk(array,size,preserve_keys);
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to use |
size | Required. | Size of each chunk |
preserve_key | Optional. | If to preserve the key |
Possible values for preserve_key:
Returns a multidimensional indexed array, starting with zero, with each dimension containing size elements.
Split an array into chunks of two.
<?php
$letters=array("A","B","C","D","E","java2s.com");
$split = array_chunk($letters,2);
print_r($split);
?>
The code above generates the following result.
Split an array into chunks of two and preserve the original keys.
<?php
$age=array("PHP"=>"5","Python"=>"7","Java"=>"3","java2s.com"=>"9");
print_r(array_chunk($age,2,true));
?>
The code above generates the following result.