Using PHP’s array_chunk() Function to Split Arrays
This article explains how the PHP array_chunk() function can divide a large array into smaller chunks of a specified size, describes its parameters, shows code examples for default behavior and key preservation, and demonstrates the resulting output.
In PHP development, splitting a large array into smaller arrays of a given size is a common task, and the array_chunk() function is designed for this purpose.
The syntax of the function is:
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )The function accepts three parameters: $array – the input array to be split; $size – the desired size of each chunk; and $preserve_keys – a boolean that determines whether the original keys are retained in the resulting chunks.
A basic example splits an array into chunks of three elements:
<?php
$array = array('a','b','c','d','e','f','g','h','i','j');
$chunks = array_chunk($array, 3);
print_r($chunks);
?>The output shows four sub‑arrays, the first three containing three elements each and the last containing the remaining element:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => d
[1] => e
[2] => f
)
[2] => Array
(
[0] => g
[1] => h
[2] => i
)
[3] => Array
(
[0] => j
)
)When the third argument $preserve_keys is set to true , the original keys are kept. The following example demonstrates this behavior:
<?php
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6);
$chunks = array_chunk($array, 2, true);
print_r($chunks);
?>The resulting array consists of three sub‑arrays, each preserving the original associative keys:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[c] => 3
[d] => 4
)
[2] => Array
(
[e] => 5
[f] => 6
)
)In summary, array_chunk() is a practical PHP function for dividing large arrays into smaller pieces, with optional key preservation, making it useful for handling extensive data sets in backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.