array_chunk()` Function Use in PHP 8.1 & PHP 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

The `array_chunk()` function in PHP splits an array into chunks of a specified size. Each chunk is returned as a separate array, and all chunks are returned within a multidimensional array.

Syntax

<?php
array_chunk(array $array, int $size, bool $preserve_keys = false): array
?>

1. $array: The input array.
2. $size: The size of each chunk.
3. $preserve_keys: When set to `true`, array keys are preserved. Default is `false`.

Example Usage in PHP 8.2

Here’s a simple example to demonstrate the `array_chunk()` function:

<?php
// Sample array
$input_array = ["a", "b", "c", "d", "e", "f", "g"];
// Chunk the array into parts of 3 elements each
$chunks = array_chunk($input_array, 3);
print_r($chunks);
?>

Output

<?php
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => d
[1] => e
[2] => f
)
[2] => Array
(
[0] => g
)
)
?>

Example with Preserved Keys

<?php
// Sample array
$input_array = ["a", "b", "c", "d", "e", "f", "g"];
// Chunk the array into parts of 3 elements each, preserving keys
$chunks_with_keys = array_chunk($input_array, 3, true);
print_r($chunks_with_keys);
?>

Output with Preserved Keys

<?php
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[3] => d
[4] => e
[5] => f
)
[2] => Array
(
[6] => g
)
)
?>

In this example, the `array_chunk()` function splits the `$input_array` into chunks of 3 elements each. By setting the third parameter to `true`, the keys of the original array are preserved in the chunks.