Home >>PHP Array Functions >PHP array_chunk() Function
PHP array_chunk() function is used to split a given input array into parts or chunks of given size depending upon the parameters passed to it. The last chunk of the array may contain fewer elements than the desired size of the chunk.It accepts three parameters $array, $size, and $preserve_keys.
Syntax:
array_chunk($array,$size,$preserve_key);
Parameter | Description |
---|---|
array | This is a requiredparameter.This parameter defines the array to use. |
size | This is a requiredparameter.This parameter definesan integer that specifies the size of each chunk. |
preserve_key | This is an optional parameter. |
Here is an example of array_chunk() function in PHP:
<html> <body> <pre> <?php $a=array("Ravi","Shubham","Jerry","Sunil","Gaurav","Rahul"); print_r(array_chunk($a,2)); ?> </pre> </body> </html>
Array ( [0] => Array ( [0] => Ravi [1] => Shubham ) [1] => Array ( [0] => Jerry [1] => Sunil ) [2] => Array ( [0] => Gaurav [1] => Rahul ) )
Example 2:
<html> <body> <pre> <?php $a=array("Ravi","Shubham","Jerry","Sunil","Gaurav","Rahul"); print_r(array_chunk($a,3)); ?> </pre> </body> </html>
Array ( [0] => Array ( [0] => Ravi [1] => Shubham [2] => Jerry ) [1] => Array ( [0] => Sunil [1] => Gaurav [2] => Rahul ) )