Master PHP’s array_chunk: Split Arrays Efficiently with Clear Examples
This guide explains PHP’s array_chunk function, detailing its syntax, parameters, and how to split large arrays into smaller chunks with or without preserving original keys, accompanied by step‑by‑step code examples and expected output.
In PHP development, handling arrays is common, and the array_chunk() function allows you to split a large array into smaller arrays of a specified size.
Function Syntax
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )The function accepts three parameters: $array – the array to be split. $size – the desired size of each chunk. $preserve_keys – optional boolean indicating whether to retain the original keys in the chunks.
Basic Example (default key handling)
<?php
$array = array('a','b','c','d','e','f','g','h','i','j');
$chunks = array_chunk($array, 3);
print_r($chunks);
?>This 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
)
)The result shows the original array successfully divided into four smaller arrays, each of size three except the final one.
Preserving Original Keys
By setting the third argument $preserve_keys to true, the original keys are retained 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 sub‑arrays that keep the original associative keys:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[c] => 3
[d] => 4
)
[2] => Array
(
[e] => 5
[f] => 6
)
)Thus, array_chunk() is a practical PHP array utility that can divide large datasets into manageable pieces, with optional key preservation, aiding developers in efficient data handling.
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.
