English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
array_chunk()Функция принимает массив в качестве входных данных и разбивает его на более мелкие блоки заданного размера. В зависимости от кратности количества элементов в массиву, последний блок может содержать меньше элементов, чем переданный размер.
array array_chunk ( array $input, int $size [, bool $preserve_keys] );
Номер | Параметры и описание |
---|---|
1 | $input (обязателен) Это массив, который нужно разделить на более мелкие блоки. Это обязательный параметр. |
2 | $size(required) We want to split theinputform to split the size of each block passed to the 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 isfalseit 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 initially introduced in PHP version 4.2.0.
If the passedsizeless than 1, it will triggerE_WARNINGand return NULL.
Let's try a simple example, splitting the array into multiple blocks, each block consisting of 2 elements-
<?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 index value as if it were 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 a warning message is triggered-
<?php //Specify the split array with size 0, an error will be thrown $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