Using PHP's array_chunk() Function to Split Arrays
This article explains how the PHP array_chunk() function can split a large array into smaller chunks of a specified size, describes its parameters, and provides code examples showing both default behavior and key‑preserving splits.
In PHP development, handling arrays is a common task, and sometimes you need to split a large array into several smaller arrays of a specified size, which is where the array_chunk() function comes into play. This article introduces the usage of array_chunk() and provides several code examples.
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 size of each resulting chunk.
$preserve_keys – a boolean that determines whether the original keys are preserved in the chunks (default is false ).
Below is a simple example that splits an array into chunks of size 3:
<?php
$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
$chunks = array_chunk($array, 3);
print_r($chunks);
?>The output shows the original array divided into four sub‑arrays, each containing three elements except the last one, which contains a single 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
)
)By default the keys are re‑indexed, but you can preserve the original keys by passing true as the third argument. The following example demonstrates this:
<?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 result is three sub‑arrays that retain 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, the array_chunk() function is a practical tool for splitting large arrays into smaller pieces and optionally preserving the original keys, which can simplify many backend data‑processing scenarios in PHP.
php8, here I come
Scan the QR code to receive free learning materials
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.