Use array_chunk() array function in PHP 7.2, PHP 7.3 & PHP 7.4 With Example

The `array_chunk()` function in PHP 7.2, PHP 7.3 & PHP 7.4 splits an array into chunks of a specified size. If the array can’t be evenly divided, the last chunk will contain the remaining elements.

Here’s the syntax:

array_chunk(array $array, int $size, bool $preserve_keys = false): array

$array: The input array.
$size: The size of each chunk.
$preserve_keys: Optional. When set to `true`, the function preserves the keys of the original array. If set to `false` (default), it resets the keys in the chunks.

Example 1: Without Preserving Keys

<?php
$array = ["a", "b", "c", "d", "e"];
$chunked_array = array_chunk($array, 2);
print_r($chunked_array);
?>

Output:-

Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)

In this example, the array is split into chunks of 2 elements each. The keys are reset.

Example 2: Preserving Keys

<?php
$array = ["a", "b", "c", "d", "e"];
$chunked_array = array_chunk($array, 2, true);
print_r($chunked_array);
?>

Output:

Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[2] => c
[3] => d
)
[2] => Array
(
[4] => e
)
)