The array_chunk Function

The array_chunk function splits a one-dimensional array into a two-dimensional one. Its first parameter is the array, and the second is the number of elements in each subarray.

Syntax

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

Example

Let's split the array into chunks of two elements each:

php<?php
  $arr = ['a', 'b', 'c', 'd'];
  
  $res = array_chunk($arr, 2);
  var_dump($res);
?>

Code execution result:

php[['a', 'b'], ['c', 'd']];

Example

Let's split the array into chunks of 3 elements each. Note that the last subarray has two elements instead of 3, as there were not enough elements left:

php<?php
  $arr = ['a', 'b', 'c', 'd', 'e'];
  
  $res = array_chunk($arr, 3);
  var_dump($res);
?>

Code execution result:

php[['a', 'b', 'c'], ['d', 'e']];