What is the use of array_chunk() function in PHP?
array_chunk() splits an array into smaller arrays (chunks) of the size that you give. The syntax is array_chunk(array, size, preserve_keys).
<?php
$numbers = [1, 2, 3, 4, 5];
echo json_encode(array_chunk($numbers, 2)) . "<br>";
$data = ["a" => 1, "b" => 2, "c" => 3];
echo json_encode(array_chunk($data, 2, true));
?>
Output:
Tutorials Class - Output Window
[[1,2],[3,4],[5]]
[{“a”:1,”b”:2},{“c”:3}]
The last chunk can be smaller. By default the keys are not kept, pass true as the third parameter to keep them. It is useful to show items in rows or to process a big array in parts.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |