Current Location: Home> Function Categories> array_chunk

array_chunk

Split the array into blocks
Name:array_chunk
Category:Array
Programming Language:php
One-line Description:Split an array into new array chunks.

PHP function: array_chunk

[Function name]

array_chunk

[Applicable to PHP version]

PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8

[Function Description]

The array_chunk function divides an array into multiple array chunks, each containing a specified number of elements. This function is often used to split large datasets into smaller parts for easier processing or paging.

[Function Syntax]

 <span class="fun">array_chunk(array $array, int $length, bool $preserve_keys = false): array</span>

[parameter]

  • $array : Required. The original array to be split.
  • $length : Required. The size (number of elements) of each new array.
  • $preserve_keys : optional. If set to true , the key name of the original array is retained; otherwise, it will be re-indexed.

[Return Value]

Returns a multidimensional array where each element is an array block of length $length . The length of the last block may be less than the specified length.

[Example]

 $input = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]; $result = array_chunk($input, 2); print_r($result); [Explanation of sample code] $input = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]; $result = array_chunk($input, 2); print_r($result);

In this example, the original array contains 5 elements, which are divided by array_chunk into multiple array chunks of 2 elements per set. The result is a multidimensional array containing 3 subarrays, namely:

  • [0] => ['a', 'b']
  • [1] => ['c', 'd']
  • [2] => ['e']

Because the $preserve_keys parameter is not set or set to false , the key name is re-indexed to numeric keys starting with 0.

Similar Functions
Popular Articles