The array_chunk
method is used to split an array into multiple arrays of a specific length.
array_chunk(array $array, int $length, bool $preserve_keys = false): array
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 to true
, the array’s keys while splitting are maintained. Otherwise, for each chunk of the array, a numeric reindex will happen.
This method returns a multidimensional array as a result. The returned array is numerically indexed from 0
.
<?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));?>
In the code above, we split the array into different lengths with and without preserving keys of the array, using the array_chunk
method.