In PHP, array_chunk() is a very useful function that can split a large array into multiple small arrays. This function is especially suitable for splitting the data into smaller parts for more efficient processing when processing large amounts of data.
The array_chunk() function is used to split an array into multiple small arrays, and returns a two-dimensional array containing multiple small arrays. The size of each small array is specified by you. If the length of the original array cannot be exactly divisible by the small array size, the last small array may contain the remaining elements.
array_chunk(array $array, int $size, bool $preserve_keys = false): array
$array : The original array of input.
$size : The size of each small array.
$preserve_keys (optional): Whether to preserve the key name of the original array. If set to true , the key name of the original array will be retained; if false (default), the key name will be reorganized into a number index starting from 0.
This function returns a two-dimensional array containing multiple small arrays.
Suppose we have a large array and we need to split it into multiple small arrays:
<?php
// Original large array
$bigArray = range(1, 15);
// use array_chunk Split array,Each small array contains 4 Elements
$chunkedArray = array_chunk($bigArray, 4);
// Output result
print_r($chunkedArray);
?>
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
)
[3] => Array
(
[0] => 13
[1] => 14
)
)
If you want to preserve the original key name of the array, you can do it by setting $preserve_keys to true . For example:
<?php
// Original large array,With custom key name
$bigArray = [10 => 'a', 20 => 'b', 30 => 'c', 40 => 'd', 50 => 'e', 60 => 'f'];
// use array_chunk Split array,and keep the key name
$chunkedArray = array_chunk($bigArray, 2, true);
// Output result
print_r($chunkedArray);
?>
Array
(
[0] => Array
(
[10] => a
[20] => b
)
[1] => Array
(
[30] => c
[40] => d
)
[2] => Array
(
[50] => e
[60] => f
)
)
As you can see, when preserve_keys is set to true , array_chunk() retains the key name of the original array.
array_chunk() is a very practical function in PHP, especially when dealing with large-scale data, which can help you split large arrays into multiple small arrays. By adjusting the size of each small array and whether to retain the key name, you can handle the data flexibly.
In actual development, array_chunk() is widely used, especially in scenarios such as paging, batch processing, and data splitting. Hope this article helps you better understand and use this function.