In this tutorial, you shall learn about PHP array_chunk() function which can split a given array into arrays of chunks with specific number of elements in each split, with syntax and examples.

PHP array_chunk() Function

PHP array_chunk() function splits the given array into arrays of chunks with specific number of elements.

You can mention the specific number of elements that has to go in each chunk.

Syntax of array_chunk()

The syntax of PHP array_chunk() function is

</>
Copy
array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] ) : array

where

ParameterDescription
arrayThe array which will be split into chunks.
sizeThe number of elements in each chunk.
preserve_keysIf TRUE, keys of the source array will be preserved.
If FALSE, keys of the chunks will reindex.

Return Value

The array_chunk() function returns an array of arrays, i.e., multi-dimensional array. Outer dimension is for the chunks, and the inner dimension is for the elements of the array.

Examples

1. Split given array into chunks of size 3

In this example, we will take an associative array with key-value pairs, and then split into chunks of size 3.

PHP Program

</>
Copy
<?php
$array = ["a"=>2, "b"=>5, "c"=>7, "e"=>9, "f"=>1, "g"=>0, "h"=>8, "i"=>3];
$chunks = array_chunk($array, 3);
echo "The chunks are";
foreach ($chunks as $chunk) {
    echo "<br>";
    print_r($chunk);
}
?>

Output