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:
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 totrue
, 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
Output:
In this example, the original array is split into chunks of 3 elements each.
Example 2: Preserving Keys
Output:
In this example, the keys of the original array are preserved in the chunks.
Example 3: Chunking an Empty Array
Output:
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.