PHP array_chunk() Function (original) (raw)

Last Updated : 19 Sep, 2024

The **array_chunk() function is an inbuilt function in PHP which is used to split an array into parts or chunks of given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk.

**Syntax

_array array_chunk( array,array, array,size, $preserve_keys )

**Parameters

This function accepts three parameters as shown in the above syntax. The parameters are described below:

**Return value

This function returns a multidimensional array indexed starting from 0. Each chunk contains _$size number of elements, except the last chunk which may contain lesser number of elements.

**Example 1: Basic usage of array_chunk() Function

PHP `

`

Output

Array ( [0] => Array ( [0] => a [1] => b )

[1] => Array
    (
        [0] => c
        [1] => d
    )

[2] => Array
    (
        [0] => e
    )

)

**Example 2: Preserving Keys with array_chunk() function

PHP `

`

Output

Array ( [0] => Array ( [0] => a [1] => b )

[1] => Array
    (
        [2] => c
        [3] => d
    )

[2] => Array
    (
        [4] => e
    )

)

**Reference: http://php.net/manual/en/function.array-chunk.php