Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_chunk() function

Reference for PHP array_chunk(): split an array into groups of a fixed size, keep the original keys if needed, and handle the shorter last chunk.

array_chunk() splits an array into smaller arrays ("chunks") of a given size and returns them as a list. All chunks have the requested size except possibly the last one, which holds whatever is left over.

Typical uses are batching work (insert 100 rows at a time), building table rows and grids from a flat list, and simple pagination.

PHP
<?php
print_r(array_chunk([1, 2, 3, 4, 5], 2));
// [[1, 2], [3, 4], [5]]

Try it

PHP Chunks of a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Keys and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_chunk(array $array, int $length, bool $preserve_keys = false): array
Name Description
$array The array to split.
$length The size of each chunk. Must be at least 1.
$preserve_keys If true, the original keys are kept inside each chunk. By default every chunk is a list numbered from 0.

Return value: a list of chunk arrays (empty if the input is empty).

Errors: a ValueError is thrown if $length is less than 1.

Usage notes

  • The last chunk may be shorter. Do not assume every chunk has exactly $length elements.
  • Keys are dropped by default, including string keys. Pass true to keep them, which is usually what you want for associative data.
  • Memory: the function builds all chunks at once. For huge inputs that you only need to process once, consider a generator or a loop with array_slice().
  • Number of chunks: to split into a fixed number of parts instead, compute the size with ceil(count($a) / $parts).
  • Strings: use str_split() to split text into pieces of equal size.
  • Columns: chunking a flat list gives rows; to get columns of a grid, combine it with array_column() or array_map(null, ...$rows).