PHP array_chunk() Function

Quick summary: The PHP array_chunk() function splits an array into chunks.

PHP array_chunk() Syntax

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

PHP array_chunk() Basic examples

var_dump(array_chunk([1,2,3,4], 2));
PHP
Output:
array(2) {
  [0]=> array(2) { [0]=> int(1) [1]=> int(2) }
  [1]=> array(2) { [0]=> int(3) [1]=> int(4) }
}

Splits an array into chunks of equal size.

PHP array_chunk() Real-world usage

$items = range(1, 5);
$pages = array_chunk($items, 2);
var_dump($pages);
PHP
Output:
array(3) {
  [0]=> array(2) { [0]=> int(1) [1]=> int(2) }
  [1]=> array(2) { [0]=> int(3) [1]=> int(4) }
  [2]=> array(1) { [0]=> int(5) }
}

Used for pagination or batching.

PHP array_chunk() Edge cases

var_dump(array_chunk(['a'=>1,'b'=>2], 1, true));
PHP
Output:
array(2) {
  [0]=> array(1) { ["a"]=> int(1) }
  [1]=> array(1) { ["b"]=> int(2) }
}

Preserves keys when the third argument is true.

PHP array_chunk() Common mistakes

Losing keys unintentionally

Keys are reset by default.

Incorrect
array_chunk(['a'=>1,'b'=>2], 1);
Correct
array_chunk(['a'=>1,'b'=>2], 1, true);

Enable key preservation when needed.

PHP array_chunk() Frequently Asked Questions

What does array_chunk() do?

Splits an array into chunks.

Syntax?

array_chunk(array, size, preserve_keys).

Preserve keys?

Optional.

Does it modify array?

No.

Use case?

Pagination or batching.

Handles associative arrays?

Yes.

Performance?

Good.

Chunk size limit?

Any integer.

Empty array?

Returns empty array.

Supports nested arrays?

Yes.

Maintains order?

Yes.

Alternative?

Manual slicing.

PHP array_chunk() Related PHP Functions