How to Split Large PHP Arrays with array_chunk – A Step‑by‑Step Guide
This article explains the PHP array_chunk() function, covering its syntax, parameters, and how to split a large array into smaller chunks with optional key preservation, illustrated by clear code examples and their resulting output.
In PHP development, dividing a large array into smaller chunks is a common need, and the array_chunk() function provides a straightforward solution.
Function Syntax
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. $preserve_keys – optional boolean indicating whether to retain the original keys in the resulting chunks (default false).
Basic Example (no key preservation)
<?php
$array = array('a','b','c','d','e','f','g','h','i','j');
$chunks = array_chunk($array, 3);
print_r($chunks);
?>The above code splits a 10‑element array into chunks of three, producing four sub‑arrays (the last containing a single element). The output is:
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
)
)Preserving Original Keys
By setting the third argument $preserve_keys to true, the original keys are kept in each chunk.
<?php
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6);
$chunks = array_chunk($array, 2, true);
print_r($chunks);
?>This produces three chunks, each retaining the associative keys:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[c] => 3
[d] => 4
)
[2] => Array
(
[e] => 5
[f] => 6
)
)Conclusion
The array_chunk() function is a practical tool for PHP developers, enabling easy division of large arrays into manageable pieces while optionally preserving original keys, which simplifies handling of extensive data sets in backend applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
