PHP array_chunk() Function
The array_chunk() function is built-in function in PHP. The array_chunk function splits an array into chunks of new arrays. This function divides an array into different block of new arrays.
Syntax
array_chunk(array,size,preserve_key);
Parameters
Parameter | Description | Is compulsory |
---|---|---|
array | Specifies the name of the array to sort. | Compulsory |
size | Integer that specifies the size of each chunk. | Compulsory |
preserve key | When set to TRUE, keys will be preserved. Default is FALSE, which will re-index the chunk numerically. | Optional |
Important Note: The last chunk may contain less elements than the desired size of the chunk.
Example
<?php
$animals=array ("DOG", "CAT", "LION", "ELEPHANT", "MONKEY", "TIGER");
print_r( array_chunk ($animals,2 ));
?>
Output
Array ( [0] => Array ( [0] => DOG [1] => CAT) [1] => Array ( [0] => LION [1] => ELEPHANT ) [2] => Array ( [0] => MONKEY
[1] => TIGER ) )
PHP Example
<?php
$input_array = array ('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2, true));
?>
Output
Array ( [0]=> Array ( [0]=> a [1]=> b ) [1]=> Array ( [2]=> c [3]=> d ) [2]=> Array ( [4]=> e ) )
PHP Example
<?php
$name = array('ajay', 'sonoo', 'rahul', 'sid', 'raj');
print_r(array_chunk($name, 4));
print_r(array_chunk($name, 2, true));
?>
Output
Array ( [0] => Array ( [0] => ajay [1] => sonoo [2] => rahul [3] => sid ) [1] => Array ( [0] => raj ) ) Array ( [0] => Array
( [0] => ajay [1] => sonoo ) [1] => Array ( [2]=>rahul [3] => sid ) [2] => Array ( [4] => raj ) )
PHP Example
<?php
$company=array("a"=>"Adobe","b"=>"Bosch","c"=>"Cummins","d"=>"Dlf");
print_r(array_chunk($company,2,true));
?>
Output
Array ( [0] => Array ( [a] => Adobe [b] => Bosch ) [1] => Array ( [c] => Cummins [d] => Dlf ) )