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
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?