PHP array_chunk() Function

In this tutorial, we will learn how we can split an array into chunks using the array_chunk() method provided in the PHP standard library.

PHP array_chunk() Function

An array in PHP is a data structure that stores a collection of values, such as numbers or strings, in a linear order. It can be created by using the array() constructor or by using square brackets [] with comma-separated values inside.

Function Syntax

The following demonstrates the function definition:

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

Function Parameters

The function accepts three main parameters:

  1. array - represents the input array on which the function is applied.
  2. length- this parameter defines the size of each chunk.
  3. preserve_keys - this is a boolean value that determines whether the keys of the array are preserved or not. If set to False, the function will re-index the chunks in a numerical pattern.

Function Return Value

The function will return a multidimensional, numerically indexed array starting with 0 for each dimension.

NOTE: The function will return a ValueError if the value of the length parameter is less than 1.


The following example demonstrates how to use the array_chunk() method to divide the array into various chunks.

// define an input array
$inputArray = array('apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape');

// divide the input array into three chunks
$chunks = array_chunk($inputArray, 3);

// output the chunks

In this case, we define an input array containing 7 elements. We then use the array_chunk() function to divide the array into three chunks with each chunk containing three elements. The last chunk will contain less than 3 elements as the input array is not divisible equally by the chunk size.

Resulting output:

    [0] => Array
            [0] => apple
            [1] => banana
            [2] => cherry

    [1] => Array
            [0] => date
            [1] => elderberry
            [2] => fig

    [2] => Array
            [0] => grape


And there you have it.


In this tutorial, we explored how we can use the array_chunk() function in PHP in order to split an input array into various number of chunks.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.