php.array_chunk()
An array in PHP is a data structure that stores a collection of values, such as numbers or strings, in a linear order. It can be created by using the array() constructor or by using square brackets [] with comma-separated values inside.
In this tutorial, we will learn how we can split an array into chunks using the array_chunk()
method provided in the PHP standard library.
Function Syntax
The following demonstrates the function definition:
array_chunk(array $array, int $length, bool $preserve_keys = false): array
Function Parameters
The function accepts three main parameters:
array
- represents the input array on which the function is applied.length
- this parameter defines the size of each chunk.preserve_keys
- this is a boolean value that determines whether the keys of the array are preserved or not. If set toFalse
, the function will re-index the chunks in a numerical pattern.
Function Return Value
The function will return a multidimensional, numerically indexed array starting with 0 for each dimension.
NOTE: The function will return a ValueError
if the value of the length
parameter is less than 1.
Example
The following example demonstrates how to use the array_chunk()
method to divide the array into various chunks.
// define an input array
$inputArray = array('apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape');
// divide the input array into three chunks
$chunks = array_chunk($inputArray, 3);
// output the chunks
print_r($chunks);
In this case, we define an input array containing 7 elements. We then use the array_chunk()
function to divide the array into three chunks with each chunk containing three elements. The last chunk will contain less than 3 elements as the input array is not divisible equally by the chunk size.
Resulting output:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
[2] => cherry
)
[1] => Array
(
[0] => date
[1] => elderberry
[2] => fig
)
[2] => Array
(
[0] => grape
)
)
And there you have it.
Conclusion
In this tutorial, we explored how we can use the array_chunk()
function in PHP in order to split an input array into various number of chunks.