PHP array_chunk() function


The array_chunk() function in PHP is used to split an array into smaller arrays (chunks) of a specified size. This function is particularly useful for processing large arrays in manageable pieces, allowing for better handling of data during iteration or display.

Syntax:

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

Parameters:

  • $array: The input array that you want to split into chunks.
  • $size: The size of each chunk (i.e., the number of elements in each smaller array).
  • $preserve_keys: (Optional) A boolean value that determines whether to preserve the original keys of the array. The default value is false, which means the keys will be re-indexed starting from 0 in each chunk. If set to true, the original keys will be preserved in the chunks.

Return Value:

  • The function returns a multidimensional array containing the chunks. Each chunk is an array itself, and if the input array is empty, it returns an empty array.

Example 1: Basic Usage

<?php $array = range(1, 10); // Create an array with values from 1 to 10 // Split the array into chunks of size 3 $chunks = array_chunk($array, 3); print_r($chunks); ?>

Output:

Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 [1] => 8 [2] => 9 ) [3] => Array ( [0] => 10 ) )

In this example, the original array is split into chunks of 3 elements each.

Example 2: Preserving Keys

<?php $array = array("a" => "Apple", "b" => "Banana", "c" => "Cherry", "d" => "Date"); // Split the array into chunks of size 2, preserving keys $chunks = array_chunk($array, 2, true); print_r($chunks); ?>

Output:

Array ( [0] => Array ( [a] => Apple [b] => Banana ) [1] => Array ( [c] => Cherry [d] => Date ) )

In this example, the keys of the original array are preserved in the chunks.

Example 3: Chunking an Empty Array

<?php $array = []; // An empty array // Split the empty array into chunks $chunks = array_chunk($array, 2); print_r($chunks); ?>

Output:

Array ( )

As expected, chunking an empty array returns an empty array.

Practical Usage:

  • The array_chunk() function is useful in various scenarios, such as:
    • Paging through results in a web application.
    • Processing large datasets in smaller parts.
    • Dividing data for batch processing or display purposes.

Summary:

  • array_chunk($array, $size, $preserve_keys) splits an array into smaller arrays (chunks) of a specified size.
  • You can choose whether to preserve the original keys of the array in the chunks.
  • This function is handy for handling large datasets and improving the manageability of array data in PHP.