What is the array_chunk method in PHP?
The array_chunk method is used to split an array into multiple arrays of a specific length.
Syntax
array_chunk(array $array, int $length, bool $preserve_keys = false): array
Arguments
-
array: The array to be split. -
length: The number of elements in each split array. The last split array may contain fewer elements than length. -
preserve_keys: A Boolean value. When set totrue, the array’s keys while splitting are maintained. Otherwise, for each chunk of the array, a numeric reindex will happen.
Return type
This method returns a multidimensional array as a result. The returned array is numerically indexed from 0.
Code
<?php$input_array = array('one' => 1,'two' => 2,'three' => 3,'four' => 4,'five' => 5);echo "Chunk array into length - 2, without preserving keys";print_r(array_chunk($input_array, 2));echo "Chunk array into length - 3, with preserving keys";print_r(array_chunk($input_array, 3, true));?>
Explanation
In the code above, we split the array into different lengths with and without preserving keys of the array, using the array_chunk method.