English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
array_chunk()The function takes an array as input and splits the array into smaller blocks of the given size. The actual number of elements in the last array block may be less than the size passed, depending on the multiple of the total number of available elements in the array.
array array_chunk ( array $input, int $size[, bool $preserve_keys] );
Serial number | Parameters and descriptions |
---|---|
1 | $input (required) This is the input array we want to split into smaller blocks. This is a required parameter. |
2 | $size (required) We want to split the array with $inputform to split the size of each block of the passed array. This is also a required parameter. |
3 | reserve_keys (optional) This is an optional boolean parameter, but when it is set totruewhen, all keys in the array will be retained. If it is not passed, its default value isfalsethis will re-index the blocks in numerical order. |
The PHP array_chunk() function returns a multidimensional numeric indexed array starting from zero, each dimension contains size elements.
This function was originally introduced in PHP version4.2introduced in version .0.
If the passedsizeless than1will causeE_WARNINGand returns NULL.
Let's try a simple example, dividing an array into multiple blocks, each block consists of2elements-
<?php $input = array('abc', 'bcd', 'cde', 'def', 'efg'); print_r(array_chunk($input, 2)); ?>Test and see‹/›
This will produce the following result, try to observe the index of each smaller array, all three blocks start from zero-
Array ( [0] => Array ( [0] => abc [1]] => bcd ) [1]] => Array ( [0] => cde [1]] => def ) [2]] => Array ( [0] => efg ) )
Let's try the same instance again, but this time we will set the parameterpreserve_keysSet to true:
<?php $input = array('abc', 'bcd', 'cde', 'def', 'efg'); print_r(array_chunk($input, 2, true)); ?>Test and see‹/›
This will produce the following result, this time each element retains its original index value as if it were retained in the original array-
Array ( [0] => Array ( [0] => abc [1]] => bcd ) [1]] => Array ( [2]] => cde [3]] => def ) [2]] => Array ( [4]] => efg ) )
The following example passes a 0 value to the size parameter, therefore causing a warning message-
<?php //Specifying a split into an array of size 0 will throw an error $input = array('abc', 'bcd', 'cde', 'def', 'efg'); print_r(array_chunk($input, 0)); ?>Test and see‹/›
Output result
PHP Warning: array_chunk(): Size parameter expected to be greater than 0 in main.php on line 3